Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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))
like image 381
heretoinfinity Avatar asked Dec 07 '16 03:12

heretoinfinity


2 Answers

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.

like image 75
MSeifert Avatar answered Nov 05 '22 09:11

MSeifert


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)

like image 3
M Kemp Avatar answered Nov 05 '22 08:11

M Kemp