Concatenating strings

You can concatenate (combine) strings in Python using the plus sign.

Consider the following example:

name = 'Mike'
surname = 'Tyson'

full_name = name + surname

print(full_name)

>>>
MikeTyson
>>>

In the output above you can see that I’ve stored the name and surname into two separate variables. I’ve then used the + sign to combine them into a single variable (full_name) which was then printed on the screen. However, the text was combined without a space in between (MikeTyson). You can insert a space like this:

full_name = name + " " + surname

>>>
Mike Tyson
>>>

In the example above I’ve combined the name variable, a space, and the surname variable.

Consider another example of concatenation:

age = 30

print('You are ' + age + ' years old.')

The code above will produce an error:

Traceback (most recent call last):
File "strings.py", line 12, in <module>
print ('You are ' + age + 'years old.')
TypeError: must be str, not int

The TypeError occured because I’ve tried to combine an integer value (30) with a string. We need to explicitly specify that we want Python to use the integer as a string of characters. We can do this by using the str() function:

age = 30

print ('You are ' + str(age) + ' years old.')

>>>
You are 30 years old.
>>>

Notice also how I’ve left a space behind are and before years, so that the output would be displayed correctly.

Geek University 2022