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

2
  • I think you can easily adapt the solution here: stackoverflow.com/questions/9244909/… Commented Nov 17, 2016 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}.]' Commented Nov 17, 2016 at 14:49

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that's the way I would have done it to begin with. I wondered if there was a better way...
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.