I want to check the string and see if at least one of the characters in the string is a letter or number. How would i do this?
Asked
Active
Viewed 6,118 times
3 Answers
3
You could use re.search
if re.search(r'[a-zA-Z\d]', string):
It will return a match object if the string contain at-least a letter or a digit.
Example:
>>> s = "foo0?"
>>> re.search(r'[a-zA-Z\d]', s)
<_sre.SRE_Match object; span=(0, 1), match='f'>
>>> s = "???"
>>> re.search(r'[a-zA-Z\d]', s)
>>> s = "???0"
>>> re.search(r'[a-zA-Z\d]', s)
<_sre.SRE_Match object; span=(3, 4), match='0'>
>>>

Avinash Raj
- 172,303
- 28
- 230
- 274
-
Never noticed that python 3 changed the `repr` of match objects, that's nice. – stranac Feb 26 '15 at 15:00
-
So would the "foo0" then return as true? – xsammy_boi Feb 26 '15 at 15:03
3
str.isalnum
:
In [16]: s = "foo"
In [17]: s.isalnum()
Out[17]: True
In [20]: s = "123"
In [21]: s.isalnum()
Out[21]: True
In [22]: s = "foo123"
In [23]: s.isalnum()
Out[23]: True
Then use any:
any(x.isalnum() for x in s)
In [24]: s = "!@1"
In [25]: any(x.isalnum() for x in s)
Out[25]: True
In [27]: s = "!@()"
In [28]: any(x.isalnum() for x in s)
Out[28]: False
It will short circuit if we find any alpha or numeric character or return False if the string contains neither.

Padraic Cunningham
- 176,452
- 29
- 245
- 321
-
I guess the op expects "%*&^%A" to return `True` as well, since "at least one character" is a letter. – Falko Feb 26 '15 at 14:55
0
Another solution might be (don't forget to import string
):
any(c in s for c in string.letters + string.digits)
(In contrast to the regex solution this is locale-dependent, e.g. including German umlauts etc.)

Falko
- 17,076
- 13
- 60
- 105