Python String Concatenation

String concatenation is likely something you will need sooner or later. Python offers several possibilities to fulfill this task. Here we will present two of the most common methods. The first method is using the +-operator. The following snippet provides an example:

>>> "foo" + "bar"
'foobar'

Here the two strings are combined into a new string, using the +-operator. Very similar to what you might find in other languages.

The second popular method uses lists and “join”, as shown in the following example:

>>> "".join(["foo", "bar"])
'foobar'

Here the strings in the list are >joined< with the string/character the join function was called on. This method is very similar to using string buffers in others languages.

Both methods are fine to use, but many Python programmers prefer the first method over the second, because it seems more readable. Functionally there is no difference and from a performance standpoint there usually is little difference between the two in practice. However, when performance is critical, it is always sensible to benchmark the two methods and then make a decision.

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.