Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally including additional characters using python string formatting

Tags:

python

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?

like image 586
derek73 Avatar asked Aug 11 '26 19:08

derek73


1 Answers

Why don't you use strip():

>>> format_string = "{last}, {first}"
>>> name = {'first': 'John', 'last':''}
>>> format_string.format(**name).strip(', ')
>>> 'John'
like image 120
Aamir Rind Avatar answered Aug 14 '26 07:08

Aamir Rind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!