Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python operator precedence when concatenating adjacent string literals

Tags:

python

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?

like image 382
Justin Chang Avatar asked Nov 19 '25 01:11

Justin Chang


1 Answers

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"
like image 82
Uri Goren Avatar answered Nov 21 '25 15:11

Uri Goren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!