Concatenate strings in Python In Python, you may concatenate strings in different ways. Which way to use depends on the scenario or string source. Following are the ways covered in this guide to concatenate strings in Python: Using + (plus) Using += concatenate operator The join() method – For iterators Using StringIO The space between string literals
An example of ‘+’ operator to combine strings If you have fewer strings to concatenate then you may use the ‘ +’ operator. You may use this operator as follows:
Using the ‘+=’ operator to concatenate two strings In this example, two string objects are concatenated by using the ‘ += ‘ operator. Have a look:
String concatenation in Python using join() example This is the efficient way of concatenating strings in Python if you have many strings. However, the join() method works with iterators like lists, tuples , etc. The official recommendation is to place many strings into a list and then use the join() method to combine them by using a separator as shown in the example below. A list of a few string elements is created and the join() method is used to return a concatenated string:
Concatenating string literals example The last example is pretty simple; if you have a few string literals to concatenate then just use a space. Well, this apparently is the least required but possible:
A demo of StringIO for concatenating strings The other recommended way for efficiently concatenating string objects is using the StringIO from the IO module . See the following example of using StringIO for combining strings: