是否可以使用python的字符串格式仅在变量不为空时有条件地包含其他字符和字符串变量?
>>> 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'
Run Code Online (Sandbox Code Playgroud)
我想使用相同的format_string变量来处理dict中first或者last在namedict 中的空值或非空值的任意组合.
在python中最简单的方法是什么?
为什么不使用strip():
>>> format_string = "{last}, {first}"
>>> name = {'first': 'John', 'last':''}
>>> format_string.format(**name).strip(', ')
>>> 'John'
Run Code Online (Sandbox Code Playgroud)