We saw previously that Python is able to combine the + operator with a string, in order to display a message on the screen. For example this code will print the word “Hello “ and will then print whatever is inside the name variable alongside it. This is known as string concatenation.
Note the necessity to include a “ “ space character in order for the print function not to just combinewordsinanunreadableway.
However, as in many programming languages, there are multiple ways to do things like this within Python. Concatenation in fact creates each string in memory, and then takes all of the strings it has memorised and combines them to form a new string — which is not very efficient in memory terms. It is also pretty picky about what it will combine:
Ah seriously Python, why the error here?! Python only likes concatenating strings — and the number 2 here is, well, a number. Python is telling us this because we have a TypeError — the item 2 must be a string, not an integer. So we could do this:
Here we are converting the number 2 into a str — into a string datatype. Python is entirely comfortable with this now, but it is a bit of a bind. Consider this more real-world code:
You would think that you need a str here to change the number you have typed in from being a number, into being a string. However, sneakily if you use the input command, Python already converts everything into a string for you. This is both very useful and also quite annoying because it can catch newbies off guard.
The rule of using concatenation is — only use it when you know that your variables, or your datatypes, are strings. If necessary, convert them to strings with str. Or, consider alternatives — which is exactly what will do next.