Tl;dr: Join strings together with exactly one space between non-blank
text where they join.
I propose a meaning for
s1 & s2
where s1 and s2 are strings.
Namely, that it should be equivalent to
s1.rstrip() + (' ' if (s1.strip() and s2.strip()) else '') +
s2.lstrip()
Informally, this will join the two strings together with exactly one space
between the last non-blank text in s1 and the first non-blank text in s2.
Example: " bar " & " foo " == " bar
foo "
This operator is associative, so there is no ambiguity in expressions
such as
s1 & s2 & s3
There *is* a possible ambiguity in expressions such as
s1 & s2 + s3
where the relative precedence of `&` and `+` matters when s2 consists
solely of white space. E.g.
" A " & " " + " C" would evaluate
to " A C"
not to " A C"
because `+` has a higher precedence than '&'.
Utility:
In decades of experience with another language which had such an
operator
(spelt differently) I have frequently found it useful for constructing
human-readable output (e.g. log output, debug/error messages,
on-screen labels).
Cognitive burden:
This would of course be one more thing to learn.
But I suggest that it is fairly intuitive that
s1 + s2
s1 & s2
both suggest that two strings are being combined in some way.
Bars to overcome:
This change would require no fundamental change to Python;
just adding an `__and__ function to the str class.
Backward compatibility:
Given that `str1 & str2` currently raises TypeError,
this change would be close to 100% backward-compatible.
Alternative meanings:
As far as I know nobody has ever suggested an alternative meaning
for `&` on strings.
Bikeshedding:
(1) I don't think it is important for the utility of this change
whether `&` strips off all whitespace, or just spaces.
I think it is better if it strips off all whitespace,
so that it can be understood as working similarly to strip().
(2) The definition could be simplified to
s1.rstrip() + ' ' + s2.lstrip()
(leave an initial/final space when one string is whitespace only).
Again the operator would be associative.
Again I don't think this is important.
Rob Cliffe
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/66XP7GY56XU7H3P52IJENLSWJFW53XIN/
Code of Conduct: http://python.org/psf/codeofconduct/