3

The docs say that two string literals that are next to each other are concatenated. For example:

>>>print("py" "thon")
python

However, this feature is implemented at compile time instead of runtime like the + and * operators, so this interesting effect occurs:

>>>print(2 * "py" + "thon")
pypython
>>>print(2 * "py" "thon")
pythonpython

I understand why this happens in the language, but I can't think of a reason for it to be that way. Is there a reason, or was it just easier to leave it alone?

Justin Chang
  • 194
  • 12
  • It is yet another loophole around pythons requirement to put things on a single line. – little_birdie Aug 14 '17 at 13:38
  • I guess this is happening because python does not treat the literal concatenation as an operation in the first case. https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation – Dhruv Aggarwal Aug 14 '17 at 13:38

1 Answers1

1

Quite frankly, If I were to design python today, I would make

print ("py" "thon")

A syntax error

Same as

print (5 3)

I would guess that the reason for concatenating adjacent strings, is for consistency with bash / perl

echo "py""thon"
Uri Goren
  • 13,386
  • 6
  • 58
  • 110
  • That's a good point. Now that I think of it, I know of no scenario where you won't be able to use a + operator. – Justin Chang Aug 14 '17 at 13:37
  • 1
    There are good reasons to allow string literal concatenation for visualization purposes (see: https://stackoverflow.com/questions/2504536/why-allow-concatenation-of-string-literals). However, the question is about why this is implemented at compile time rather than run time – Chris_Rands Aug 14 '17 at 13:44