Format string with possible non-existing arguments in Python -
i've searched this, i'm not sure how word i'm asking, it's difficult find whether has posted solution.
i'd format variables descriptive string. example:
'my name {name}. eat {food}.'.format(name='ben', food='pizza') gives (obviously): 'my name ben. eat pizza.'
but i'd omit entire second sentence in case food none or '' (empty). so:
'my name {name}. eat {food}.'.format(name='ben', food='') gives: 'my name ben.'
is there can wrap around second sentence make conditional on there being non-blank value of food? can in inelegant way joining strings , suchlike, looking more pythonic solution. perhaps need subclass formatter, i'm not sure start that.
(as aside, know winamp used able in format strings depending on whether tags present or not in mp3 file.)
its question, way work around
food = "pizza" food = "i eat {food}".format(food = food) print ('my name {name}.%s'.format(name='ben')%(food if food else "")) # >>> name ben.i eat pizza food = "" food = "i eat {food}".format(food = food) print ('my name {name}.%s'.format(name='ben')%(food if food else "")) # >>> name ben.
Comments
Post a Comment