benshepherd
benshepherd

Reputation: 725

Format string with possible non-existing arguments in Python

I've searched for this, but I'm not sure how to word what I'm asking, so it's difficult to find whether somebody has already posted a solution.

I'd like to format some variables into a descriptive string. As an example:

'My name is {name}. I like to eat {food}.'.format(name='Ben', food='pizza')

gives (obviously): 'My name is Ben. I like to eat pizza.'

But I'd like to omit the entire second sentence in the case that food is None or '' (empty). So:

'My name is {name}. I like to eat {food}.'.format(name='Ben', food='')

gives: 'My name is Ben.'

Is there something I can wrap around the second sentence to make it conditional on there being a non-blank value of food? I can do this in an inelegant way by joining strings and suchlike, but I was looking for a more Pythonic solution. Perhaps I need to subclass Formatter, but I'm not sure where to start with that.

(As an aside, I know that Winamp used to be able to do this in format strings depending on whether tags were present or not in an MP3 file.)

Upvotes: 2

Views: 338

Answers (2)

benshepherd
benshepherd

Reputation: 725

OK, here's a nice way that I just thought of (I've slept on it).

def taciturn(format_string, **args):
    return format_string.format(**args) if any(args.values()) else '' 

print('My name is {name}. {food_preference}'.format(name='Ben', food_preference=taciturn('I like to eat {food}.', food='pizza'))

Similar to @ari-gold's answer but (perhaps) a little more elegant. I still don't like it though.

Upvotes: 0

Ari Gold
Ari Gold

Reputation: 1548

its a good question, this way is a work around

food = "Pizza"
FOOD = "I like to eat {food}".format(food = food)
print ('My name is {name}.%s'.format(name='Ben')%(FOOD if food else ""))
# >>> My name is Ben.I like to eat Pizza


food = ""
FOOD = "I like to eat {food}".format(food = food)
print ('My name is {name}.%s'.format(name='Ben')%(FOOD if food else ""))
# >>> My name is Ben.

Upvotes: 1

Related Questions