Remove some characters from a string

J

Julien

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:
str: 'si_98udasgf'

Would you have any hint?

Thanks a lot!

Julien
 
C

Chris

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:


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^[email protected]*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)
 
P

Paul Hankin

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:


str: 'si_98udasgf'

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

import string

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

Fredrik Lundh

Julien said:
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:

str: 'si_98udasgf'

the easiest way is to replace the things you don't want with an empty
string:
'si_98udasgf'

("\W" matches everything that is "not numbers, letters, or underscores",
where the alphabet defaults to ASCII. to include non-ASCII letters, add
"(?u)" in front of the expression, and pass in a Unicode string).

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top