I am trying to parse text and determine if it contains only letters and numbers, not special keyboard symbols like ! and #. I tried using .isalpha, but it says ! and # are valid. Is there away I can have something return false if it encounters one of these symbols?
Asked
Active
Viewed 65 times
-1
-
also dup of http://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-string-in-python – CRABOLO Mar 29 '14 at 01:21
-
`>>> '!'.isalpha() False` Lying when asking a question isn't the best way to obtain an answer... – Bakuriu Mar 29 '14 at 14:19
2 Answers
1
Use regex matching:
import re
print re.match(r'^\w+$',your_string).group(0)
This matches the whole string only if it is alphanumeric
>>> print re.match(r'^\w+$', '1kjh2431k2j43').group(0)
'1kjh2431k2j43'
>>> print re.match(r'^\w+$', 'hjs7*Y@#kha9Y*@#').group(0)
NoneType

sshashank124
- 31,495
- 9
- 67
- 76
0
can check if the ordinals of the characters are in the ranges of characters, think the ranges are like 65-90ish and then 95-122ish, and then just check .isdigit() to see if the number was a digit beforehand

Snoop Dogg
- 62
- 3
-
Welcome to StackOverflow, and thanks for your answer. Since this question is marked as a duplicate, you should take a look at the referenced question and see if you can improve the answers there. This helps to avoid repetition and guide people to the best available answers. – Richard Neish Apr 02 '14 at 09:34