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

后端 未结 2 2000
情深已故
情深已故 2021-02-19 16:54

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

2条回答
  •  别那么骄傲
    2021-02-19 17:28

    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.

提交回复
热议问题