[Python-ideas] Dedicated string concatenation operator
Ken Hilton
kenlhilton at gmail.com
Wed Jun 20 07:51:46 EDT 2018
Hi all, just another wild idea.
I've been working a lot with PHP lately (boo!), and one of the things I
have a love-hate relationship with in it is its string concatenation
operator: .
Counter-intuitively to Python, `.` is used to concatenate strings; `"str1"
. "str2"` evaluates to `"str1str2"`.
Even though it's kind of weird, I find the separation between addition and
concatenation useful. In PHP, `"str1" + "str2"` evaluates to 0; `"str1" .
"str2"` evaluates to `"str1str2"`. Obviously, in Python, `"str1" + "str2"`
could not evaluate to 0, it should instead raise a TypeError. But it's more
clear what is going on here:
$content .= "foobar";
$i += 1;
than here:
content += "foobar"
i += 1
I propose adding a dedicated operator for string concatenation. I don't
propose `.` as that operator - that would break too much. My initial idea
is to abuse the @ operator introduced for matrix multiplication to work for
string concatenation when applied to strings. This would be an example
result of that:
>>> from numpy import matrix
>>> matrix('1 2; 3 4') @ matrix('4 3; 2 1')
[[ 8 5]
[20 13]]
>>> "str1" @ "str2"
"str1str2"
>>> "str1" @ 56 #str() is called on 56 before concatenating
"str156"
>>> 56 @ "str1" #str would also have __rmatmul__
"56str1"
>>> content = "foobar"
>>> content @= "bazbang"
>>> content @= "running out of ideas"
>>> content
'foobarbazbangrunning out of ideas'
However, the operator does not necessarily have to be @ - I merely picked
that because of its lack of use outside matrix math.
What are your thoughts?
Sincerely,
Ken Hilton;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180620/db9ae677/attachment.html>
More information about the Python-ideas
mailing list