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

String formatting for different options in python

我想打印一个字符串,描述从列表中删除了多少项 ('count') 以及因此留在列表中的项数。为了使其在语法上正确,我有以下代码:

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 的方法来实现这一点?

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

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)))