python中不同选项的字符串格式

时间:2015-04-19 15:49:15

标签: python string-formatting

我想打印出一个字符串,用于描述从列表中删除的项目数(“计数”)以及列表中剩余的项目数量。为了使其语法正确,我有以下代码:

if count == 1:
    print("\n{} definition was removed. We therefore currently have {} definitions to test...".format(count, len(test_list)))
if count > 1:
    print("\n{} definitions were removed. We therefore currently have {} definitions to test...".format(count, len(test_list)))    

是否有更多的Pythonic方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

在您的情况下,您只有一个变量参数was/were,它根据count的值而变化。为了使代码更具可读性,您只能更改变量,而不是格式化整个消息。

msg = '"\n{} {} removed. We therefore currently have {} definitions to test..."'
prep = 'definition was'
if count > 1:
    prep = 'definitions were'

print(msg.format(count, prep, len(test_list)))