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,Python 3 Documentation
"hello" 'world'is equivalent to
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.
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.
x = ‘py’ ‘thon’
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!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.