可选的字符串格式

时间:2017-02-08 17:18:25

标签: python string

是否可以改进此代码:

if isinstance(value, bool) and value:
    cms = "%s %s" % (cms, usage_map["switches"][switch])
else:
    cms = "%s %s %s" % (cms, usage_map["switches"][switch], value)

只用一行?使值可选吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用:

cms = '{} {}{}'.format(
    cms, usage_map["switches"][switch],
    '' if isinstance(value, bool) and value else ' {}'.format(value)
)

答案 1 :(得分:0)

你可以写:

cms = "%s %s" % (cms, usage_map["switches"][switch])
if isinstance(value, bool) and value:
    cms += " %s" % value

另外,我认为您可以将条件重写为:if value is True: