Detect if a string contains special characters or not in Python
Let us see how to detect a string whether it contains special characters or not in Python.
When we speculate about this, our mind initially says us to use functions by defining them. But today let us see the same scenario using the functions from regular expressions module.
Let us see the usage of some functions from regular expressions in Python.
To check if a string has special characters or not in Python
We can use re.match(), re.search(), re.sub() functions for detecting the special characters from the string.
The above-mentioned functions all belong to RegEx module which is a built-in package in Python.
Let us see how to use re.match() for detecting the string has a special character or not.
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.
o="hai" import re if(bool(re.match('^[a-zA-Z0-9]*$',o))==True): print("valid") else: print("invalid")
Here is the output for the above code.
This is also a function in the RegEx module. This is similar to re.match() function. It locates a match anywhere in the string.
If you want to match at the beginning of the string or to match the entire string use match. It is faster.
As we are checking whether the special character is present or not we can use re.search().
p="hai#" import re if(bool(re.search('^[a-zA-Z0-9]*$',o))==True): print("valid") else: print("invalid")
Let us see the output now.
We can also detect if a string has special character or not by importing “string” and using string.punctuation.
string.punctuation to detect if a string contains special characters or not in Python
“string.punctuation” is a pre-initialized string used as a string constant. This returns all sets of punctuation.
Let us see the code now.
import string x="hello" invalidcharacters= set(string.punctuation) if any(char in invalidcharacters for char in x): print ("invalid") else: print("valid")