print() function can concatenate for us if strings are given as arguments, why not just use this instead of concatenating with
To answer this let’s start by looking at the print function (for more details about
+ concatenation check the other FAQs). Here you can see the full documentation for the print function (at time of writing python 3.8 is the latest). So looking at the print function:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
You can see that there are a few arguments here, we are going to only look at
sep=' ' for the purposes of this lesson. To quote the documentation " Print objects to the text stream file , separated by sep."
*objects, is any number of different objects that will all be printed together, for example our list of
string1, string2, string3, etc.. Usefully, any non string objects will be converted by default using
str(), unlike if we used concatenation. And the seperator is an argument that for a string that is placed between each object. By default it is a single space
' ', but you could change it if you wished for example by setting
sep=', ', now there is a comma then a space.
So far this seems more useful and easier than concatenation, but there is a catch. The separator is placed between all objects. This means we cannot mix and match. For example:
string1 = 'My favorite number' num = 14 string2='is the best number' print(string1+': '+str(num)+' '+string2) >My favorite number: 14 is the best number
So concatenation is going to be more useful overall for putting together custom sentences with variables while the print function is going to be more useful for “stringing” together similar types of objects (words in a sentence, numbers in a list, etc.)
I hope this helps!