[Python-ideas] New explicit methods to trim strings
rosuav at gmail.com
Sun Mar 24 05:04:20 EDT 2019
On Sun, Mar 24, 2019 at 7:43 PM Alex Grigoryev <evrial at gmail.com> wrote:
> Following the discussion here I propose to add 3 new string methods: str.trim, str.ltrim, str.rtrim
> Another option would be to change API for str.split method to work correctly with sequences.
> In : def ltrim(s, seq):
> ...: return s[len(seq):] if s.startswith(seq) else s
> [corresponding functions snipped]
You may need to clarify here one of two options: either ltrim accepts
*only and precisely* a string, not an arbitrary sequence (as your
parameter naming suggests); or that it accepts an arbitrary sequence,
but with different semantics to your example. With str.startswith, any
sequence can be accepted, and if the string starts with *any* of the
strings, it will return True:
>>> "abcd".startswith(("ab", "qw", "12"))
Your simple one-liner would take the length of the tuple (3) and
remove that many characters. From the BPO discussion, I suspect you
actually just want to use a single string here, but I could be wrong,
especially with the suggestion to make str.split work with sequences;
do you mean that you want to be able to split on any string in the
sequence, or split arbitrary sequences, or something else?
(Another option here - since an email address won't usually contain a
colon - would be to use s.replace("mailto:", "") to remove the prefix.
Technically it IS valid and possible, but it's not something I see in
the wild, so you're unlikely to break anyone's address by removing
"mailto:" out of the middle of it.)
For complicated string matching and replacement work, you may need to
reach for the 're' module. Yes, I'm aware that then you'll have two
problems, but it's in the stdlib for a reason.
More information about the Python-ideas