Remove some characters from a string
cwitts at gmail.com
Thu Jul 17 11:03:26 CEST 2008
On Jul 17, 10:13 am, Julien <jpha... at gmail.com> wrote:
> 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!
One quick and dirty way would be...
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