[Python-ideas] New explicit methods to trim strings

Christopher Barker pythonchb at gmail.com
Tue Mar 26 11:14:25 EDT 2019

> And this really is simple enough that I don't want to reach for regex's
>> for it. That is, I'd write it by hand rather than mess with that.
> Well, with re.escape it's not messy at all :
You could do a ltrim function in one line :
> def ltrim(s, x):
>     return re.sub("^" + re.escape(x), '', s)
> I think
>     re.sub("^" + re.escape(x), '', s)
> is a lot more messy and hard to read than
>     s[len(prefix):] if s.startswith(prefix) else s
> it's also roughly an order of magnitude slower.

I agree, but I said I wouldn’t choose to “mess” with regex, not that the
resulting code would be messy.

There is a substantial cognitive load in working with regex—they are
another language.  If you aren’t familiar with them (I’m not) it would take
some time, and googling, to find that solution.

If you are familiar with them, you still need to import another module and
end up with an arguably less readable and slower solution.

Python was designed from the beginning not  to rely on regex for simple
string processing, opting for fairly full featured set of string methods.
These two simple methods fit well into that approach.


Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190326/33a92ff6/attachment.html>

More information about the Python-ideas mailing list