Python Basics Tutorial 5 – Python String Concatenation
Notes from the video ‘Python Course Singapore | Learn Python Programming |Python Tutorial 5 – Python String Concatenation’:
In Python, you can combine 2 or more strings with a plus sign (+). This is called concatenation.
Let’s try an example.
Let’s say we want Python to display Good morning!, you can do this with just one variable, for example, if you were to type:
statement = “Good morning”
Python displays Good Morning.
Another way we can do this is by concatenation. We can break “Good Morning” down into two parts and assign each part to a separate variable and combine the words e.g.
first_word = “Good”
second_word = “morning”
We can combine the 2 strings with a plus sign (+) e.g.
complete_text = first_word + second_word
Python displays Goodmorning.
Note that when you concatenate the two strings, Python doesn’t automatically add spaces or punctuation when you concatenate strings. So, you need to include a space in the first string after the text “Good”.
Now, let’s try printing complete_text again.
Alright, this time Python displays Good morning with a space between the words.
You can also concatenate a string and a variable.
For example, if we were to concatenate the string “Good “ and the variable second_word and print them, we would also get the same result.
Another important thing to note that is that you cannot concatenate a string to a number, otherwise you would get an error.
Let’s try it out.
If we were to concatenate the string “Hi “ and the number 5, we would get an error message.
One way to go around this is to convert the number 5 to a string first.
Now, if we were to concatenate the strings “Hi “ and “5” together, Python displays Hi 5.