Remove some characters from a string

Paul Hankin paul.hankin at
Thu Jul 17 11:13:08 CEST 2008

On Jul 17, 9:13 am, Julien <jpha... at> wrote:
> Hi,
> I can't seem to find the right regular expression to achieve what I
> want. I'd like to remove all characters from a string that are not
> numbers, letters or underscores.
> For example:
> >>> magic_function('si_98%u^d at .as-*gf')
> str: 'si_98udasgf'

For speed, you can use 'string.translate', but simplest is to use a

import string

def magic_function(s, keep=string.ascii_letters + string.digits +
    return ''.join(c for c in s if c in keep)

Paul Hankin

More information about the Python-list mailing list