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
Adding many strings is disapproved because:
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.