Python String Concatenation Without ‘+’

When I first saw this, I was sure it’s a bug. Well—it’s a feature!

In today’s short article, you’ll learn about a small Python trick that I call “string concatenation without +”. Let’s start with some code!

Plus vs. Adjacent String Literal Concatenation

>>> 'Fin' 'xter'
'Finxter'
>>> 'Fin' + 'xter'
'Finxter'

There are two ways to concatenate string literals in Python:

  • Using the + operator between two string literals. This also works for variables.
  • Using adjancent string literals without the + operator. This doesn’t work for variables.

Does Adjacent String Concatenation Work For Variables?

No. Here’s a counter example:

>>> x = 'Fin'
>>> y = 'xter'
>>> x + y
'Finxter'
>>> x y
SyntaxError: invalid syntax

The reason can be found in the documentation:

Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld".

Python 3 Documentation

Where to Use Adjacent String Concatenation?

You can use adjacent string concatenation to reduce the number of backslashes (to escape the newline character) or to split strings conveniently across lines, or even to add comments to parts of strings.

Here’s an example where you use the string concatenation of adjacent strings in the regex findall function to use comments to explain parts of the string.

import re

x = re.findall('[A-Za-z]' # Pattern Part 1: Upper or Lowercase
               '[a-z]+',  # Pattern Part 2: Lowercase Letters
               'Hello World')
print(x)
# ['Hello', 'World']

Note how this would be a bit confusing when using string concatenation with the plus + operator:

import re

x = re.findall('[A-Za-z]' # Pattern Part 1: Upper or Lowercase
               + '[a-z]+',  # Pattern Part 2: Lowercase Letters
               'Hello World')
print(x)
# ['Hello', 'World']

The meaning is the same but it would be somehow confusing due to the overloaded meaning of the + operator for string concatenation and within the regex.

Can You Solve the Puzzle?

A well-designed puzzle conveys one single point that surprises the reader.

[python]
x = ‘py’ ‘thon’
print(x)
[/python]

What is the output of this code snippet?

You can check whether you solved this puzzle correctly in our interactive Finxter app! Are you a master coder?
Test your skills now!

Related Video