Reputation: 5672
Is it possible using python's string format to conditionally include additional characters along with the string variable only if the variable is not empty?
>>> format_string = "{last}, {first}"
>>> name = {'first': 'John', 'last':'Smith'}
>>> format_string.format(**name)
'Smith, John' # great!
>>> name = {'first': 'John', 'last':''}
>>> format_string.format(**name)
', John' # don't want the comma and space here, just 'John'
I would like to use the sameformat_string
variable to handle any combination of empty or non-empty values for first
or last
in the name
dict.
What's the easiest way to do this in python?
Upvotes: 3
Views: 350
Reputation: 176
You can set value for separator based on condition.
'{first}{separator}{last}'.format(**{"first":first, "last":last,"separator":(", " if last and first else "")})
Upvotes: 1
Reputation: 39669
Why don't you use strip():
>>> format_string = "{last}, {first}"
>>> name = {'first': 'John', 'last':''}
>>> format_string.format(**name).strip(', ')
>>> 'John'
Upvotes: 6
Reputation: 15170
You could run the original dict through a function to 'clean' it, adding commas where appropriate. Or, have a defaultdict.
The following solution, the simplest, does a post-process step to remove any extra commas and spaces:
import re
name = {'first': 'John', 'last':''}
format_string = '{last}, {first}'
def fixme(instr):
return re.sub('^, ', '',
re.sub(', $', '',
instr))
print fixme(format_string.format(**dict(first='John', last='')))
print
print fixme(format_string.format(**dict(first='', last='Smith')))
John
Smith
Upvotes: 0