Why should we use concatenation instead of just the print() function?

Question

The print() function can concatenate for us if strings are given as arguments, why not just use this instead of concatenating with +?

Answer

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 *objects, and sep=' ' for the purposes of this lesson. To quote the documentation " Print objects to the text stream file , separated by sep."
The argument *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!

Hi all :slight_smile:

So there’s two ways to print a concatenated string with a number in it:

  1. Make the number a string first with the str() function, then print(it + with + other + stuff)
  2. Don’t do 1, just print(it, inside, this, function)

What’s the reason behind these two methods? Why use 1) and not 2) ?

12 Likes

should be more simple?

7 Likes

I guess you could put all of the strings into a variable to put inside the print() function…
Not really more simple, just easier to understand though.

2 Likes

@py1184336943

Look at the difference between the spacing of your solution and the “print(message)” solution. I just started and had the same thought, but I noticed right away that it prints the spaces between each string differently. I wonder if a later lesson covers that wider space.

4 Likes

I think this is because when you use print in this way it adds a space after each argument. There are already spaces included in the test string, like here: "The Wind, " - the result of this is a double space after each test string. You could test this by removing the spaces from the text string, like so: “The Wind,” instead of "The Wind, " and so on

3 Likes

Yes, because as @catower explained in his answer to another question above, the default separator for the print() function is a space.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
That’s what sep=’ ’ means above.

Just like one of the benefits of using concatenation is customizing the outputted string, one of the benefits of passing arguments to print() with commas is it will automatically add the space for you. (Or a ‘,’ or a ', ’ or a ‘;’ depending on however you want the arguments to be separated.)

3 Likes

Disclaimer: Still pretty new, so feedback on this answer would be greatly appreciated!

From what I understand, we’ll be using concatenation in multiple different ways, not just to print. So, in the event that you’re not just doing a simple print() function, and you need to combine a number with another string, you would be able to do that by turning the number into a str() first.

Again not totally sure, but I think the point of converting the number to a str() is so that other functions outside of print() (which can understand the number on its own) can reference it in a concatenation.

Does this sound right to anyone else?

5 Likes

Yes, im really new my self, but when i made a calculator + a reference “program” i did this,
I don’t remember exactly how(cant find my file) but i put a day into learning python during dead time at work, but stopt because we got a huge workload.

Since we’re also so early in on the course, It’s always a good thing to think that it can be used this way, but as we go we will learn that there are better ways to do this. So instead of getting “caught up” on this just move on and come back to it later when you are more experienced and it still hasn’t been answered, it allows you to both put what you learnt into use and give you a project which could motivate you to get better

Edit: a number can be turned into a string by adding ’ ’ to the number or result. Hence there is no need to make reference to a number by str()

Making sure that I understood the content of the answer correctly:

  • print() allows to quickly put objects that are similar together - as long as there is no need for syntax or language to be considered

  • Thus, lists (numbers, ingredients, etc.), short quotes or phrases, would be more effectively written with print() with the use of commas (,) between each component

  • For anything requiring more customization, more language and vocabulary heavy, and putting more emphasis on the syntax of the language, the use of concatenation would be better as it allows a much easier adjustment of the syntax of the produced statement.

  • Here is an analogy to showcase what is the usefulness of concatenation: It is much easier to move a group of words around in order to fix a paragraph rather than moving each individual word.

  • Concatenation allows to move groups of words

  • While print() allows to move singular words

Let me know if my understanding is correct or erroneous. :slight_smile:

1 Like

message = ("%s %s %s %s %s %s")

words = (“The wind,”, “which had hitherto carried us along with amazing rapidity,”, “sank at sunset to a light breeze;”, “the soft air just ruffled the water and”, “aused a pleasant motion among the trees as we approached the shore”, “from which it wafted the most delightful scent of flowers and hay”)

print(message%words)

Regarding this:
birthday_string = “I am "
age = 10
birthday_string_2 = " years old today!”

Concatenating an integer with strings is possible if we turn the integer into a string first

full_birthday_string = birthday_string + str(age) + birthday_string_2

Prints “I am 10 years old today!”

print(full_birthday_string)

Why wouldn’t I just write this:
birthday_string = “I am 10 years old today!”
print(birthday_string)

1 Like

In your birthday_string, “10” is a pair of static characters. They aren’t variables that can be changed or used in a calculation. The output of the 2 print functions is the same in the exercise and in your version, but the underlying logic to get there is completely different.

2 Likes

Disclaimer: Super New…I mean SUPER NEW to coding. Since there are plenty of ways to display what we type in, what is the difference between using print(“put words here”) and using string concatenation or print(put, words, here) if they all display the same thing?

I’m incredibly new to this, but the only thing that I can see from this example though is the spacing in what gets displayed. Not sure I’m fully understanding this correctly…

@argentinespice this is similar to the example that @method0954638387 gave above and as @xhackerxzerox explains:

Simply printing the words using your example print(“put words here”) is very static and not flexible especially if it contains variables that can be changed by other inputs.

For example, imagine if you are coding a generic greeting based on user inputs of name and birth year. If you had just used the print function with the static words, you would not be able to swap out the message for each individual and have zero flexibility.

But if they are variables, you can use concatenation to create dynamic messages like this:

#These are variables users can change name = "Jon Snow" birth_year = 1980 #this can automatically be updated via datetime in Python current_year = 2023 #This is a derived variable age = current_year - birth_year #Template for birthday greeting birthday_greeting = "Happy " + str(age) + " birthday " + name + "!" #Final message that's dynamic based on input print(birthday_greeting)

You can change the name and birthday in the above code as many times as you like without having to hard code it. This is a simplified example, but imagine if you have lots of millions of data users and you have all the user info stored in a database. It would be insane to hard code the message for each user AND refreshing it every year. With this, you can just pull the age and name from the data to create the birthday greeting.

Think for example how Facebook create and sends the birthday reminders. They have a template with the print message ready to be populated with names and birthdays.

As for your other question, as explained in the OP post the default separator in the print function is a single space. Thus when @py1184336943 did this you get an extra space between each string because the strings already contain the space needed. In general, concatenation allows more flexibility on how the objects are combined, whereas using print function separating the arguments by comma is better if how you are combining them is static (always a space in between, comma between words, etc.)

birthday_string = “I am”
age = 10
birthday_string_2 = “years old today”
message = birthday_string + " " + str(age) + " " + birthday_string_2 + “!”

Output is
I am 10 years old today!
Do not understand why this is being rejected and I keep getting the message “message not as expected”

Any fixes? Thx.

Hi, my two cents…
I am new to python and doing the data scientist path. Loving it so far. But just as some others here I find concatenation a bit confusing.

Right now working on a task in “Python Syntax: Medical Insurance Project” where I should have used concatenation. This was the preferred way to do it, mentioned in a hint:

age = 28 sex = 0 bmi = 26.2 num_of_children = 3 smoker = 0 insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children +24000 * smoker - 12500 print("This person's insurance cost is " + str(insurance_cost) + " dollars.")

But I got the same result with this:

print("This person's insurance cost is ",insurance_cost," dollars.")

So why would the first way the right way? Very curious to find out!