Skip to content
Advertisement

Is the implicit conversion of strings that have only whitespace between them to a single string any different from concatenation?

I came across this line in the Python documentation:

String that are part of a single expression and have only whitespace between them will be implicitly converted to a single string literal. That is, (“spam ” “eggs”) == “spam eggs”.

Another way to see this is,

"spam" "eggs" == "spam" + "eggs"

Firstly, apart from the concept that ‘explicit is better than implicit”, is there any ‘under the hood’ difference in using either or..? But also, what is the reason behind permitting this syntax in Python..?

I hadn’t given it thought before, but is this why separating strings across multiple lines while enclosing them within parenthesis works as a syntax for defining multi-line strings, such as:

text = (
        "This is a single "
        "sentence, typed "
        "across three lines."
        )

Advertisement

Answer

The Python interpreter uses constant folding while building the AST.

Therefore, there is no difference in the runtime between "spam" "eggs" and "spam" + "eggs". Both values will be evaluated to "spameggs".

Consider the following example

import dis


a = lambda: "spam" "eggs"
b = lambda: "spam" + "eggs"

print(dis.dis(a))
print(dis.dis(b))

Note that both values have the same byte code.

dis.dis(a)
  1           0 LOAD_CONST               1 ('spameggs')
              2 RETURN_VALUE

In [6]: dis.dis(b)
  1           0 LOAD_CONST               1 ('spameggs')
              2 RETURN_VALUE
Advertisement