2

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.)

benshepherd
  • 635
  • 7
  • 18
  • I think you can easily adapt the solution here: http://stackoverflow.com/questions/9244909/python-conditional-string-formatting – Rockbar Nov 17 '16 at 14:23
  • I read that question before posting. It just doesn't look very scalable. My use case involves several more parameters than I've put in the simple example above. I was thinking of something where the optional bit is just wrapped in square brackets: `'My name is {name}. [I like to eat {food}.]'` – benshepherd Nov 17 '16 at 14:49

2 Answers2

1

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.
Ari Gold
  • 1,528
  • 11
  • 18
0

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.

benshepherd
  • 635
  • 7
  • 18