[Python-ideas] New explicit methods to trim strings
mertz at gnosis.cx
Sat Mar 30 09:03:26 EDT 2019
On Sat, Mar 30, 2019, 8:42 AM Steven D'Aprano <steve at pearwood.info> wrote:
> Most of us have had to cut a prefix or a suffix from a string, often a
> file extension. Its not as common as, say, stripping whitespace, but it
> happens often enough.
I do this all the time! I never really thought about wanting a method
though. I just spell it like this without much thought:
basename = fname.split(".ext")
But I suppose a method would be helpful. If we have one, PLEASE no
variation of 'trim' in the name. I still forget whether it's .lstrip() or
.ltrim() or .stripl() or etc. after 20 years using Python. Lots of
languages use trim for Python's strip, so having both with subtly different
meanings is a bug magnet.
One thing I love about .startswith() and .endswith() is matching multiple
options. It's a little funny the multiple options must be a tuple exactly
(not a list, not a set, not an iterator), but whatever. It would be about
to lack that symmetry in the .cut_suffix() method.
if fname.endswith(('.jpg', '.png', '.gif)): ...
I'd expect to be able to do:
basename = fname.cut_suffix(('.jpg', '.png', '.gif))
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas