I can only use a string in my program if it contains no special characters except underscore _
. How can I check this?
I tried using unicodedata library. But the special characters just got replaced by standard characters.
re. match() to detect if a string contains special characters or not in Python. This is function in RegEx module. It returns a match when all characters in the string are matched with the pattern(here in our code it is regular expression) and None if it's not matched.
You can use string.punctuation
and any
function like this
import string invalidChars = set(string.punctuation.replace("_", "")) if any(char in invalidChars for char in word): print "Invalid" else: print "Valid"
With this line
invalidChars = set(string.punctuation.replace("_", ""))
we are preparing a list of punctuation characters which are not allowed. As you want _
to be allowed, we are removing _
from the list and preparing new set as invalidChars
. Because lookups are faster in sets.
any
function will return True
if atleast one of the characters is in invalidChars
.
Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116
word = "Welcome" import re print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"
You will need to define "special characters", but it's likely that for some string s
you mean:
import re if re.match(r'^\w+$', s): # s is good-to-go
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With