小编der*_*k73的帖子

使用python字符串格式有条件地包含其他字符

是否可以使用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或者lastnamedict 中的空值或非空值的任意组合.

在python中最简单的方法是什么?

python

2
推荐指数
1
解决办法
113
查看次数

标签 统计

python ×1