Reputation: 91
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 "."
Upvotes: 5
Views: 14993
Reputation: 1
import string
s = input("Enter a string:")
if all(i in string.punctuation for i in s):
print ("Only special characters")
else:
print ("Valid")
use the above loop to set boolean events and use it accordingly
Upvotes: 0
Reputation: 107297
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!
Upvotes: 5
Reputation: 785286
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_]+$
Code:
>>> def spec(s):
if not re.match(r'^[_\W]+$', s):
print('Valid')
else:
print('Invalid')
>>> spec('Hello')
Valid
>>> spec('Hello??')
Valid
>>> spec('??')
Invalid
Upvotes: 9
Reputation: 4863
Here's the working code:
import string
def checkString(your_string):
for let in your_string.lower():
if let in string.ascii_lowercase:
return True
return False
Upvotes: 0