为什么 print("text" + str(var1) + "more text" + str(var2)) 被描述为 "disapproved"?

Why is print("text" + str(var1) + "more text" + str(var2)) described as "disapproved"?

为什么下面的代码在 'Snakes and Coffee' 对 Blender 的 Print multiple arguments in python 的 post 的评论中被称为 'age-old disapproved method' of printing?跟Python2或者Python3的后端code/implementation有关系吗?

print("Total score for " + str(name) + " is " + str(score))

它被认为是旧的,因为您可以使用 'better' 方式通过引入 python 3(以及 python 2 的更高版本)对其进行格式化。

print("Total score for "+str(name)"+ is "+str(score))

可以写成: print("Total score for %s is %s" % (name, score))

尽管在 python 2 及更高版本的更高版本中可以使用多种不同的方式设置打印格式。

上面的内容在技术上也很旧,这是 python 2 及更高版本中的另一种方法。

print('Total score for {} is {}'.format(name, score)

添加多个字符串未获批准,因为:

  • 与替代品相比,它的可读性并不高。
  • 它的效率不如替代品。
  • 如果您有其他类型,则必须对它们手动调用 str

而且,是的,它真的很旧。 :-)

理论上字符串加法会创建一个新字符串。因此,假设您添加了 n 个字符串,那么您需要创建 n-1 个字符串,但是除了一个之外的所有字符串都将被丢弃,因为您只对最终结果感兴趣。 字符串是作为数组实现的,因此您有很多潜在的昂贵(重新)分配没有任何好处。

如果你有一个带占位符的字符串,它不仅更具可读性(它们之间没有 +str)而且 python 也可以计算多长时间最后一个字符串是,只为最后一个字符串分配一个数组并插入所有内容。

实际上这并不是真正发生的事情,因为 Python 检查字符串是否是中间字符串并进行一些优化。所以它没有创建 n-2 不必要的数组那么糟糕。

对于小字符串 and/or 交互式使用,您甚至不会注意到差异。但是其他方式的优点是更具可读性。

备选方案可以是(前两个是从@MKemps 的回答中复制的):

  • "Total score for {} is {}".format(name, score)
  • "Total score for %s is %s" % (name, score)(也老了!)
  • "Total score for {name} is {score}".format(name=name, score=score)
  • f"Total score for {name} is {score}"(非常新 - 在 Python 3.6 中引入)

特别是后两个例子表明,您甚至可以读取模板字符串而无需插入任何内容。

print 函数接受任意数量的参数,这些参数将自动转换为字符串并(默认情况下)在它们之间打印空格。所以这样写示例代码更简单:

print("Total score for", name, "is", score)

请注意,前导空格和尾随空格 未包含在字符串文字中 ,因为 print 会自动添加这些空格。如果你不想要那些自动的额外空格(或者你想要一个不同的分隔符),那么你可以在末尾传递可选的关键字参数 sep

print("Score for ", name, " is ", score, "/100", sep="")
# Score for (name) is (score)/100

请注意,这次字符串文字确实需要包含我们想要的空格,因为我们告诉 print 函数不要自动添加它们。