为什么 print(“text" + str(var1) + “more text" + str(var2)) 被描述为“不批准"? [英] Why is print("text" + str(var1) + "more text" + str(var2)) described as "disapproved"?

查看:38
本文介绍了为什么 print(“text" + str(var1) + “more text" + str(var2)) 被描述为“不批准"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码在Snakes and Coffee"对Blender 在 python 中打印多个参数?是否与 Python 2 或 Python 3 的后端代码/实现有关?

Why is the code below termed 'age-old disapproved method' of printing in the comment by 'Snakes and Coffee' to Blender's post of Print multiple arguments in python? Does it have to do with the backend code/implementation of Python 2 or Python 3?

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

推荐答案

添加多个字符串被拒绝,因为:

Adding many strings is disapproved because:

  • 与替代方案相比,它的可读性并不强.
  • 它不如其他方法有效.
  • 如果您有其他类型,则必须手动调用 str.

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

And, yeah, it is really old. :-)

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

In theory string addition creates a new string. So, just assume you add n strings, then you need to create n-1 strings but all of these except one are discarded because you're only interested in the final result. Strings are implemented as arrays so you have a lot of potentially expensive (re-)allocation for no benefit.

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

If you have a string with placeholders it is not only more readable (you don't have these + and str between them) but python can also compute how long the final string is and allocate only one array for the final string and insert everything.

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

In practice that's not really what is happening because Python checks if a string is an intermediate and does some optimization. So it's not as bad as creating n-2 unnecessary arrays.

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

For small strings and/or interactive use you wouldn't even notice a difference. But then the other ways have the advantage of being more readable.

替代方案可能是(前两个是从@MKemps 答案中复制的):

Alternatives could be (the first two are copied from @MKemps answer):

  • {} 的总分是 {}".format(name, score)
  • %s 的总分是 %s" %(姓名,分数)(也很旧!)
  • {name} 的总分是 {score}".format(name=name, score=score)
  • f"{name} 的总分是 {score}"(非常新 - 在 Python 3.6 中引入)
  • "Total score for {} is {}".format(name, score)
  • "Total score for %s is %s" % (name, score) (also old!)
  • "Total score for {name} is {score}".format(name=name, score=score)
  • f"Total score for {name} is {score}" (very new - introduced in Python 3.6)

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

Especially the latter two examples show that you can even read the template string without having to insert anything.

这篇关于为什么 print(“text" + str(var1) + “more text" + str(var2)) 被描述为“不批准"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆