Let’s look at two ways you can concatenate (which is a fancy word for join or merge) two or more strings in Python.
It’s also worth checking out our article on converting integers to strings in Python.
A Note On Immutable Strings
Strings in Python are immutable and cannot be changed once defined. This means that whenever you join two strings, a new string is created (ie. the original is not modified!).
This has both performance side effects and affects how you should structure your code:
- As a new string is created at each concatenation, if you are joining more than two strings, join() is the most efficient method to use
- You must assign the concatenation to a variable if you wish to use it again (it’s fine if this is the same variable which held one of the strings used in the concatenation)
You may not have even noticed this behavior (especially on the first point, computers these days have a lot of memory for storing text) – and many common languages have immutable strings so it may never even come up – but it’s worth pointing out!
Using ‘+‘
The easiest way to join two strings in Python:
freshness = "stale" colour = "green" fruit = "apple" joined = freshness + colour + fruit print joined # Returns "stalegreenapple"
Using ‘join()‘ to Concatenate Arrays of Strings
The above method is simple and easy to remember – however the join() function is often tidier looking and offers better performance:
words = ["fresh", "red", "apple"] joined = ','.join(words) print joined # Returns "fresh,red,apple"
Notice that we have joined the words with a ‘,’ (standard comma) – any string can be used here, or an empty string can be used if no separator is required.
Why was this better? – See the note on immutability and performance above – It is easier to read – It was super easy to add a comma between each word – to do so using ‘+‘ would have involved adding multiple extra strings which is tedious and messy.
Conclusion
Of course, this is all super simple, but it’s worth brushing up on if you’re switching from another language like PHP – particularly due to the immutability of strings which can result in unintended results if you aren’t used to that behavior.