When using the print function why should you concatenate vs using the , to send the strings in as arguments?


Question when we use the print function and we need to print out a set of strings with integers lets says something like this

print(“I would like”+ str(amount) + " Cheeseburger")
print(“I would like”, amount, " Cheeseburger")

Why would we use the first print function with concatenation vs the print function using the arguments? Isn’t it less work passing the strings as arguments vs having to use the str() function on integers?

From what I understand from research the bottom function is slower in compiling and does not work as well with larger strings. Is this true?


Hello @jcheat23, welcome to the forums! The reason you would use the first example is, on top of what you’ve said, because when saving it to a variable, it acts like a list, not like a string. For example:

#Excuse the arbitrary values and variable names
amount = 5
b = "hi", 5, "their", "to"#Acts like a list, not like a string:
c = "hi" + str(5) + "their" + "to"#more like a string
print(b)#This will print: ("hi", 5, "their", "to")
print(c)#This, however, will print: "hi5theirto"
print(b[2])#This accesses the second index of `b`. And returns…`their`-acting like a list (not a string, where each character is its own index)
print(c[2])#This does the same as the above, however returns 5 (which, if you count characters, is the 2 index in)

To summarise, using concatenation lends strings more stringy characteristics, when saving them to variables.
I hope this helps!

Your example isn’t quite an equivalent case. What you’re doing with your variable b is resulting in a tuple (not a list), and subsequently the call to print() is printing it as a tuple.

If you mean “less work for the Python interpreter”, because you’re just passing in a series of objects for it to print and omitting the call to str(), then no… not really.

This is because, if you refer to the documentation for the print() built-in function you’ll notice that when you pass in a series of objects for it to print, like:
print("I would like", amount, "Cheeseburger")
that Python converts all of them, where necessary, to strings anyway before concatenating them with the sep=" " parameter and printing the result.

Ultimately, for smaller strings like this I don’t think you’d ever see an appreciable drop in execution speed.

Keep in mind, as well, that you can also do what’s called “printf formatting”:
print("I would like %d Cheeseburger" % amount)

>>> amount = 2
>>> print("I would like " + str(amount) + " Cheeseburger")
I would like 2 Cheeseburger
>>> print("I would like", amount, "Cheeseburger")
I would like 2 Cheeseburger
>>> print("I would like %d Cheeseburger" % amount)
I would like 2 Cheeseburger
1 Like