Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

regex

If the string has an alphabet or a number, return true. Otherwise, return false.

I have to do this, right?

return re.match('[A-Z0-9]',thestring)
like image 495
TIMEX Avatar asked Jul 13 '11 09:07

TIMEX


2 Answers

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
>>> 
like image 195
DrTyrsa Avatar answered Oct 27 '22 15:10

DrTyrsa


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))

like image 35
mhyfritz Avatar answered Oct 27 '22 15:10

mhyfritz