[Python-ideas] More user-friendly version for string.translate()

Paul Moore p.f.moore at gmail.com
Mon Oct 24 17:10:04 EDT 2016


On 24 October 2016 at 21:54, Chris Barker <chris.barker at noaa.gov> wrote:
> I don't know a way to do "remove every character except these", but someone
> I expect there is a way to do that efficiently with Python strings.

It's easy enough with the re module:

>>> re.sub('[^0-9]', '', 'ab0c2m3g5')
'0235'

Possibly because there's a lot of good Python builtins that allow you
to avoid the re module when *not* needed, it's easy to forget it in
the cases where it does pretty much exactly what you want, or can be
persuaded to do so with much less difficulty than rolling your own
solution (I know I'm guilty of that...).

Paul


More information about the Python-ideas mailing list