The Python Oracle

In Python, how do I check if a string has alphabets or numbers?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind

--

Chapters
00:00 In Python, How Do I Check If A String Has Alphabets Or Numbers?
00:20 Accepted Answer Score 18
00:34 Answer 2 Score 5
01:06 Answer 3 Score 2
01:16 Thank you

--

Full question
https://stackoverflow.com/questions/6676...

--

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), or
  • bool(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)