I have a string like below:
a = "This is {} code {}"
In later part of my code, I will be formatting the string using args provided to the below function:
def format_string(str, *args):
fmt_str = str.format(*args)
print fmt_str
...
My problem here is that if number of args provided to the function format_string
is either lesser or more than the required, I get an Exception.
Instead, if args are less, I want it to print empty {} and if the args are more than required, then I want the extra args to be ignored.
i have tried to do this is several ways, but could not avoid the exception. Can anyone help please?
Update: I was able to fix this problem based on the answer provided in this post: Leaving values blank if not passed in str.format
This is my implementation:
class BlankFormatter(Formatter):
def __init__(self, default=''):
self.default = default
def get_value(self, key, args, kwargs):
if isinstance(key, (int, long)):
try:
return args[key]
except IndexError:
return ""
else:
return kwargs[key]
Had to modify the string as follows to use the above BlankFormatter on it:
a = "This is {0} code {1}"
In my format_string function, I used the BlankFormatter to format the string:
def format_string(str, *args):
fmt = BlankFormatter()
fmt_str = fmt.format(str,*args)
print fmt_str
...