Search code examples
pythonpython-3.xstring-formatting

How can I satisfy different string formatting scenarios with the same code?


I have an input file that contains string of placeholder text and associated values. I don't really know ahead of time which ones are coming though and was curious if there is a single code block that can satisfy all of the following combinations of placeholder strings and supplied values.

In essence I want this:

examples = [
    {"text": "There are {} bagels in a bakers dozen.", "values": 13},
    {"text": "My favorite bagels are {} and {}.", "values": ["cinnamon raisin", "maple"]},
    {"text": "I have not had a pop tart in 14 {}", "values": "years"}
]

for single_example in examples:
    print(single_example['text'].format(single_example['values']))

However format(single_example['values']) does not work for the second text. Instead I can do format(*single_example['values']) to allow the second example to work but it would break the first with the error IndexError: tuple index out of range and the third by slicing the string.

I think I need to make everything into a list so that format(*single_example['values']) will function across the board but I am stuck finding an approach that works for the above cases.

This works for me but I feel there might be a more streamlined approach.

for single_example in examples:
    if isinstance(single_example['values'], list):
        values = single_example['values']
    else:
        lst = []
        lst.append(str(single_example['values']))
        values = lst
    print(single_example['text'].format(*values))

Solution

  • You can have an if-else inside format if your input cannot be changed:

    examples = [
        {"text": "There are {} bagels in a bakers dozen.", "values": 13},
        {"text": "My favorite bagels are {} and {}.", "values": ["cinnamon raisin", "maple"]},
        {"text": "I have not had a pop tart in 14 {}", "values": "years"}
    ]
    
    for single_example in examples:
        print(single_example['text'].format(*single_example['values'] if isinstance(single_example['values'], (list, tuple)) else [single_example['values']]))
    
    # There are 13 bagels in a bakers dozen.
    # My favorite bagels are cinnamon raisin and maple.
    # I have not had a pop tart in 14 years