Just use str.isalnum()
>>> "123AbC".isalnum()
True
>>> "1&A".isalnum()
False
Referencing the docs:
Return true if all characters in the string are alphanumeric and there
is at least one character, false otherwise. A character c
is alphanumeric
if one of the following returns True
: c.isalpha()
, c.isdecimal()
,
c.isdigit()
, or c.isnumeric()
.
If you don't want str.isdigit()
or str.isnumeric()
to be checked which may allow for decimal points in digits just use str.isnumeric()
and str.isalpha()
:
>>> all(c.isnumeric() or c.isalpha() for c in "123AbC")
True
>>> all(c.isnumeric() or c.isalpha() for c in "1&A")
False
And if you'd like to use re you could see vs97's answer or if you don't mind including underscores (_)
this will work fine too:
>>> re.fullmatch("\w", "123AbC", re.A)
True
>>> re.fullmatch("\w", "1&A", re.A)
False
This works because \w
matches [a-zA-Z0-9_]
when used with re.ASCI
flag, re.A
for short.
Referencing the docs again for \w
:
For Unicode (str) patterns:
Matches Unicode word characters; this includes alphanumeric characters (as defined by str.isalnum()) as well as the underscore (). If the ASCII flag is used, only [a-zA-Z0-9] is matched.