1

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
    ...
Community
  • 1
  • 1
allDoubts
  • 67
  • 8
  • 2
    Which *"several ways"* did you try, and can you be more specific about the problem that *"could not avoid the exception"*? – jonrsharpe Aug 10 '15 at 20:34
  • 2
    possible duplicate of [Leaving values blank if not passed in str.format](http://stackoverflow.com/questions/19799609/leaving-values-blank-if-not-passed-in-str-format) – skyking Aug 10 '15 at 20:37
  • Hi, I am using a list here and not a dict for formatting. I do not have keys in the string. The post that you mentioned gives a solution for getting a value by key from a dict – allDoubts Aug 10 '15 at 20:43
  • 1
    Please post the exception you are getting, as well as some of the code you have tried. – Mark Tozzi Aug 10 '15 at 21:01
  • 1
    If `args` only contains one argument, would it correspond to the first `'{}'` or the second? If it contains more than two arguments, which should be kept and which should be discarded? – TigerhawkT3 Aug 10 '15 at 21:18
  • The args from the end of the list should not be considered when args are more than required. If less, then the first {} should be filled – allDoubts Aug 10 '15 at 22:11

2 Answers2

1

There are a few different ways to do this, some of which are more or less flexible. Perhaps something like this will work for you:

from __future__ import print_function


def transform_format_args(*args, **kwargs):
    num_args = kwargs['num_args']  # required
    filler = kwargs.get('filler', '')  # optional; defaults to ''

    if len(args) < num_args:  # If there aren't enough args
        args += (filler,) * (num_args - len(args))  # Add filler args
    elif len(args) > num_args:  # If there are too many args
        args = args[:num_args]  # Remove extra args

    return args


args1 = transform_format_args('cool', num_args=2)
print("This is {} code {}.".format(*args1))  # This is cool code .

args2 = transform_format_args('bird', 'worm', 'fish', num_args=2)
print("The {} ate the {}.".format(*args2))  # The bird ate the worm.

args3 = transform_format_args(num_args=3, filler='thing')
print("The {} stopped the {} with the {}.".format(*args3))
# The thing stopped the thing with the thing.

num_args is the number of args you want, not the number that you passed in. filler is what to use when there aren't enough args.

Cyphase
  • 11,502
  • 2
  • 31
  • 32
  • Thanks! I guess this is a good solution if I use only {}. However, i implemented a different solution by adding numbers to the {} indicating which positional argument should be considered. This way I was able to catch the IndexError exception. Please see my update on the question. – allDoubts Aug 10 '15 at 22:13
0
def formatter(input, *args):
    format_count = input.count("{}")
    args = list(args) + ["{}"] * (format_count - len(args))
    print input.format(*args[:format_count])

formatter("{} {} {}", "1", "2")
formatter("{} {} {}", "1", "2", "3")
formatter("{} {} {}", "1", "2", "3", "4")

1 2 {}
1 2 3
1 2 3
user3757614
  • 1,776
  • 12
  • 10