The prog asks me to check whether any special char like !@#... are present in the given string. How can I do this?
Asked
Active
Viewed 367 times
3 Answers
0
Define a function first. Use re.search
with a pattern [^\w\s\d]
which will match anything that is not a letter, space, digit, or underscore.
In [43]: def foo(string):
...: return 'Valid' if not re.search('[^\w\s]', string) else 'Invalid'
...:
Now, you may call it with your strings:
In [44]: foo("@#example!")
Out[44]: 'Invalid'
In [45]: foo("Seemingly valid string")
Out[45]: 'Valid'

cs95
- 379,657
- 97
- 704
- 746
0
You can use re.match
to do this task.
Try :
word = "@#example!"
import re
print ("Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid")
Output :
Invalid

Md. Rezwanul Haque
- 2,882
- 7
- 28
- 45