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

余生颓废 提交于 2021-02-07 05:14:33

问题


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

回答1:


Adding many strings is disapproved because:

  • it's not really readable, compared to the alternatives.
  • it's not as efficient as the alternatives.
  • if you have other types you have to manually call str on them.

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

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.

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.

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.

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

  • "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.




回答2:


It is considered old because you can use 'better' ways to format it with the introduction of python 3 (and later versions of python 2).

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

Could be written as: print("Total score for %s is %s" % (name, score))

Although there are a multitude of different ways you can format print in later versions of python 2 and above.

What is up above is technically old as well, this is another way to do it in later versions of python 2 and above.

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



来源:https://stackoverflow.com/questions/41008941/why-is-printtext-strvar1-more-text-strvar2-described-as-disappr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!