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?
Why don't you use strip():
>>> format_string = "{last}, {first}"
>>> name = {'first': 'John', 'last':''}
>>> format_string.format(**name).strip(', ')
>>> 'John'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With