Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check when string contains only special characters in python

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 "."

like image 755
user3076097 Avatar asked Mar 04 '15 17:03

user3076097


People also ask

What does %% mean in Python?

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.

How do you check if it is a special character in Python?

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.

How do you handle special characters in a string Python?

Escape sequences allow you to include special characters in strings. To do this, simply add a backslash ( \ ) before the character you want to escape.


2 Answers

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
like image 185
anubhava Avatar answered Nov 02 '22 23:11

anubhava


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!

like image 39
Mazdak Avatar answered Nov 03 '22 00:11

Mazdak