TIMEX
TIMEX

Reputation: 271674

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

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)

Upvotes: 7

Views: 41168

Answers (5)

deftclaw
deftclaw

Reputation: 66

I know this is old but it's still relevant in search results. I'm testing in 3.9.5:

  • bool(re.match('.\*[a-zA-Z0-9].\*', 'asdf1234'))
    returns False (because we've escaped the *, which means literal asterisk not 0+ of the previous match)
  • bool(re.match('.*[a-zA-Z0-9].*', 'asdf1234'))
    works but seems like a lot of weird typing to me. Since we're invoking re it makes sense to use regex:
  • bool(re.match('[\w\d]', 'asdf1234')) is working.
  • isalnum() is also still valid in 3.9.5.

Since I'm posting today, I also checked 3.13.0 (latest at time of writing):

  • bool(re.match('[\w,\d]', 'asdf1234'))
    returns True but throws a syntax warning saying \w is invalid. what?!
  • bool(re.match('[a-zA-Z0-9]', 'asdf1234'))
    returns True without complaining.
  • bool(re.match('[\\w,\\d]', 'asdf1234'))
    returns True without complaining. what?!
  • 'asdf1234'.isalnum()
    returns True without complaining.

as @glicerico mentioned in his comment to this answer

.isalnum() returns False for strings like 'asdf1234-' because - is not alphanumeric, which the question was somewhat ambiguous about.

.isalnum() seems to be the most future-proof, assuming it meets your needs, and according to @Chris Morgan it's also the fastest. That's not surprising considering regex is generally pretty slow.

Also I have no idea wtf python 3.13.0 is doing with regex.

Upvotes: 0

ru2wen2
ru2wen2

Reputation: 158

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)

Upvotes: 2

DrTyrsa
DrTyrsa

Reputation: 31951

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

Upvotes: 18

Juan
Juan

Reputation: 1

What about

stringsample.isalpha() 

method?

Upvotes: -1

mhyfritz
mhyfritz

Reputation: 8522

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

Upvotes: 5

Related Questions