Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I whitelist characters from a string in python 3? [duplicate]

My question is quite simple, I am trying to strip any character that is not A-Z, or 0-9 from a string.

Basically this is the process I am trying to do:

whitelist=['a',...'z', '0',...'9']

name = '_abcd!?123'

name.strip(whitelist)

print(name)

>>> abcd123

What's important to know is that I can't just only print valid characters in name. I need to actually use the variable in its changed state.

like image 635
NeverEndingCycle Avatar asked Oct 25 '25 15:10

NeverEndingCycle


1 Answers

You can use re.sub and provide a pattern that exactly matches what you are trying to remove:

import re
result = re.sub('[^a-zA-Z0-9]', '', '_abcd!?123')

Output:

'abcd123'
like image 146
Ajax1234 Avatar answered Oct 27 '25 04:10

Ajax1234