[Python-ideas] Easily remove characters from a string.

M.-A. Lemburg mal at egenix.com
Sun Oct 23 08:25:03 EDT 2016


On 22.10.2016 10:34, Simon Mark Holland wrote:
> Having researched this as heavily as I am capable with limited experience,
> I would like to suggest a Python 3 equivalent to string.translate() that
> doesn't require a table as input.  Maybe in the form of str.stripall() or
> str.replaceall().
> 
> My reasoning is that while it is currently possible to easily strip()
> preceding and trailing characters, and even replace() individual characters
> from a string, to replace more than one characters from anywhere within the
> string requires (i believe) at its simplest a command like this :
> 
> some_string.translate(str.maketrans('','','0123456789'))
> 
> In Python 2.* however we could say ...
> 
> some_string.translate(None, '0123456789')
> 
> My proposal is that if strip() and replace() are important enough to
> receive modules, then the arguably more common operation (in terms of
> programming tutorials, if not mainstream development) of just removing all
> instances of specified numbers, punctuation, or even letters etc from a
> list of characters should also.
> 
> I wholeheartedly admit that there are MANY other ways to do this (including
> RegEx and List Comprehensions), as listed in the StackOverflow answer
> below.   However the same could be said for replace() and strip().
> http://stackoverflow.com/questions/22187233/how-to-delete-all-instances-of-a-character-in-a-string-in-python
> 
> This is my first suggestion and welcome any and all feedback, even if this
> is a silly idea I would really like to know why it is.  I have not seen
> discussion of this before, but if there is such a discussion I would
> welcome being directed to it.

Could you perhaps give a use case for what you have in mind ?

I usually go straight to the re module for anything that's
non-trivial in terms of string manipulation, or use my
mxTextTools for more complex stuff.

re.sub() would be the natural choice for replacing multiple
chars or removing multiple chars in one go.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Experts (#1, Oct 23 2016)
>>> Python Projects, Coaching and Consulting ...  http://www.egenix.com/
>>> Python Database Interfaces ...           http://products.egenix.com/
>>> Plone/Zope Database Interfaces ...           http://zope.egenix.com/
________________________________________________________________________

::: We implement business ideas - efficiently in both time and costs :::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611
               http://www.egenix.com/company/contact/
                      http://www.malemburg.com/



More information about the Python-ideas mailing list