
I agree. This behavior is too specialized to be implemented as an operator. + is IME so infrequently used on python strings that we should take caution when proposing new binary string operators. Two strings to concat, maybe; three, possibly; four or more, and I reach for join() or f-strings or anything else. And if we are just joining two or three strings, that is readable right now as str1.rstrip() + ' ' + str2.lstrip(). A solution that is as extensible as join, no need for operators or subclasses: def connect(iterable, /): it = iter(iterable) first = next(it, '') last = next(it, None) if last is None: return first else: parts = [first.rstrip()] for this in it: parts.append(last.strip()) last = this parts.append(last.lstrip()) return ' '.join(parts) But I would not advocate for inclusion in the standard lib as there are too many parameters the user may want to behave differently for them. Keep the trailing spaces? Leading space? Add spaces when connecting an empty string? A string that is only whitespace? Operate only on exactly str or the __str__ value of any object? Regards, Jeremiah On Tue, Mar 7, 2023 at 1:57 AM Valentin Berlier <berlier.v@gmail.com> wrote:
I'm -1 on this. You can easily make a helper that achieves the desired syntax. Presenting "human readable data" isn't just about collapsing spaces, and having your own helper means that you can adjust the formatting to your specific use case if needed (for example with a different separator).
from typing import Self
class StripJoin: def __init__(self, value: str = "") -> None: self.value = value def __and__(self, other: str) -> Self: other = other.strip() separator = bool(self.value and other) * " " return StripJoin(f"{self.value}{separator}{other}") def __str__(self) -> str: return self.value
j = StripJoin() print(j & " foo " & " bar " & " something ") # Output: "foo bar something"
The example above is more efficient than a possible implementation directly on the str builtin as it doesn't strip the left side over and over. However it still incurs repeated allocations and encourages a pattern that performs badly in loops. With a lot of input you should probably accumulate the stripped strings in a list and join them all at once.
In any case I recommend reaching out for a library like Rich ( https://github.com/Textualize/rich) if you care about formatting the output of your program nicely. _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@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/A7RPR3... Code of Conduct: http://python.org/psf/codeofconduct/