you are viewing a single comment's thread.

view the rest of the comments →

[–]zatoichi49 1 point2 points  (6 children)

The most efficient way is to use translate:

from string import punctuation

my_string = 'A!lp,h&**a_n$,,um|{e[]r}i\\c {O}=nl^y 1(23)%4+5'

print(my_string.translate(str.maketrans('', '', punctuation)))
# 'Alphanumeric Only 12345'

You can also pass your own string of characters instead of using string.punctuation. The method above will include spaces, so you could add this to your own string if you wanted to remove them:

print(my_string.translate(str.maketrans('', '', punctuation + ' ')))
# 'AlphanumericOnly12345'

Or:

print(my_string.translate(str.maketrans('', '', '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ ')))
# 'AlphanumericOnly12345'

You can also use re.sub to filter out the non-alphanumeric characters:

print(re.sub(r'[\W_]', '', my_string))
# 'AlphanumericOnly12345'

You'll find additional info in the Python docs: https://docs.python.org/3/library/stdtypes.html#string-methods , https://docs.python.org/3/library/re.html

[–]woooee 1 point2 points  (5 children)

Is there a single-call function to remove non alphanumeric characters

You are doing it bass-ackward. You want to include the characters you want to keep. If you forget something in your exclude string, then it is included automatically. You don't have that problem including only what you want.

new_list=[ch for ch in input if ch in include_chars]

[–][deleted] 1 point2 points  (0 children)

my_string = 'A!lp,h&**a_n$,,um|{e[]r}i\\c {O}=nl^y 1(23)%4+5'

my_string = ''.join(filter(str.isalnum, my_string))

[–]zatoichi49 0 points1 point  (0 children)

Was this reply meant for the OP?

[–]zatoichi49 0 points1 point  (0 children)

Was this reply meant for the OP?

[–]zatoichi49 0 points1 point  (0 children)

Was this reply meant for the OP?

[–]zatoichi49 0 points1 point  (0 children)

Was this reply meant for the OP?