So what I want to do is check if the string contains only special characters. An example should make it clear
Hello -> Valid
Hello?? -> Valid
?? -> Not Valid
Same thing done for all special characters including "."
When you see the % symbol, you may think "percent". But in Python, as well as most other programming languages, it means something different. The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand.
We are using the re. match() function to check whether a string contains any special character or not. The re. match() method returns a match when all characters in the string are matched with the pattern and None if it's not matched.
Escape sequences allow you to include special characters in strings. To do this, simply add a backslash ( \ ) before the character you want to escape.
You can use this regex with anchors to check if your input contains only non-word (special) characters:
^\W+$
If underscore also to be treated a special character then use:
^[\W_]+$
RegEx Demo
Code:
>>> def spec(s):
if not re.match(r'^[_\W]+$', s):
print('Valid')
else:
print('Invalid')
>>> spec('Hello')
Valid
>>> spec('Hello??')
Valid
>>> spec('??')
Invalid
You can use a costume python function :
>>> import string
>>> def check(s):
... return all(i in string.punctuation for i in s)
string.punctuation contain all special characters and you can use all
function to check if all of the characters are special!
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