Remove some characters from a string
Chris
cwitts at gmail.com
Thu Jul 17 05:03:26 EDT 2008
On Jul 17, 10:13 am, Julien <jpha... at gmail.com> 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'
>
> Would you have any hint?
>
> Thanks a lot!
>
> Julien
One quick and dirty way would be...
import string
safe_chars = string.ascii_letters + string.digits + '_'
test_string = 'si_98%u^d at .as-*gf'
''.join([char if char in safe_chars else '' for char in test_string])
you could also use a translation table, see string.translate (the
table it uses can be made with string.maketrans)
More information about the Python-list
mailing list