In Python, how do I check if a string has alphabets or numbers?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles
--
Chapters
00:00 Question
00:24 Accepted answer (Score 17)
00:41 Answer 2 (Score 4)
01:19 Answer 3 (Score 2)
01:39 Answer 4 (Score 0)
01:52 Thank you
--
Full question
https://stackoverflow.com/questions/6676...
Accepted answer links:
[thestring.isalnum()]: http://docs.python.org/2/library/stdtype...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #regex
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles
--
Chapters
00:00 Question
00:24 Accepted answer (Score 17)
00:41 Answer 2 (Score 4)
01:19 Answer 3 (Score 2)
01:39 Answer 4 (Score 0)
01:52 Thank you
--
Full question
https://stackoverflow.com/questions/6676...
Accepted answer links:
[thestring.isalnum()]: http://docs.python.org/2/library/stdtype...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #regex
#avk47
ACCEPTED ANSWER
Score 18
Use thestring.isalnum() method.
>>> '123abc'.isalnum()
True
>>> '123'.isalnum()
True
>>> 'abc'.isalnum()
True
>>> '123#$%abc'.isalnum()
>>> a = '123abc'
>>> (a.isalnum()) and (not a.isalpha()) and (not a.isnumeric())
True
>>>
ANSWER 2
Score 5
If you want to check if ALL characters are alphanumeric:
string.isalnum()(as @DrTyrsa pointed out), orbool(re.match('[a-z0-9]+$', thestring, re.IGNORECASE))
If you want to check if at least one alphanumeric character is present:
import string
alnum = set(string.letters + string.digits)
len(set(thestring) & alnum) > 0
or
bool(re.search('[a-z0-9]', thestring, re.IGNORECASE))
ANSWER 3
Score 2
It might be a while, but if you want to figure out if the string at at least 1 alphabet or numeral, we could use
re.match('.\*[a-zA-Z0-9].\*', yourstring)