[Tutor] removing digits from a file

Tim Peters tutor@python.org
Fri, 18 May 2001 19:00:00 -0400


[sheri]
> hello, i am trying to write a script to remove digits from a list of
> spelling words.
> i have a file like this:
> 1. that 2. cat 3. rat 4. etc...
>
> i want to do something like this
>
> if char (is a digit)
>   delete char
>
> so that the output file is like this:
> that cat rat etc...

Hmm.  Since I see you got 4 replies that didn't mention the obvious solution
yet, maybe it's not really that obvious <wink>.

The string module has a translate() function that can both substitute
characters and delete them.  You don't want any substitutions here, so the
code needed to turn substituting off gets in the way a bit:

import string
dont_substitute_anything = string.maketrans("", "")

def sheri(a_string):
    return string.translate(a_string,
                            dont_substitute_anything,
                            "0123456789.") # characters to delete

Then, for example,

>>> sheri("1. that 2. cat 3. rat 4. etc...")
' that  cat  rat  etc'
>>>