Combination of Number and String
Suppose we want to place a number and a string next to each other. Since a number can also be included within a string, one solution is:
But maybe we want to concatenate a number and a string separately and print it. In string operations, adding two strings together is allowed, and it concatenates them. Do you think adding a number and a string concatenates them as well?
Which of the following statements can print a string and a number together?
Aferiniiii!!! Come, let me tell you why.
I'm sorry. Come, let me tell you why.
In Python, you can only add data of the same type together. This means a string can be added to another string, and a number can be added to another number. However, adding a string and a number is not possible and will result in a syntax error if you try to do so.
To solve this problem, there is a simple solution: using a comma. If you place a comma between a string and a number, they will be printed side by side on the same line with a space in between. Run the following example.
Let's look at some examples. What do you think the output of this code is? As always, think about it yourself before running the code.
As we mentioned, the addition of two strings concatenates them, and it doesn't matter if the string contains a number or text!
So what do you think about the following code?
This output shows how many tabs are open in the browser: 99 tabs are open
Which of the following commands cannot produce this output and will result in an error?
- The first option is correct because two strings can be concatenated together.
- The second option is incorrect because a string and a number cannot be concatenated together.
- The third option is correct because a string and a number can be combined with a comma.
- The fourth option is correct because it is a regular string and everything within the string is printed exactly as it is.
In this section, we learned how to place numbers and strings side by side. We understood that this is done using the comma operator, not the addition operator!