Reputation: 23
while this question is similar to a lot of other questions around, i feel that the specific situation i'm trying to solve here is not contemplated in the other questions.(or i'm just not understanding the solutions)
im trying to figure it out how to implement the following code:
if str[i] == (any element from list)
#do stuff
in the context of the program, the code needs to check if the specific string element is a number or a letter, but i imagine there is a simpler solution to "compare string element to every letter and number".
Upvotes: 0
Views: 71
Reputation: 22275
If you are wanting to check if a string contains only numbers or a letter you can use str.isalnum()
:
Return
True
if all characters in the string are alphanumeric and there is at least one character,False
otherwise. A characterc
is alphanumeric if one of the following returnsTrue
:c.isalpha()
,c.isdecimal()
,c.isdigit()
, orc.isnumeric()
.
Example Usage:
>>> s = 'a@'
>>> s[0].isalnum()
True
>>> s[1].isalnum()
False
>>> '@pple123.isalnum()
False
>>> 'apple123'.isalnum()
True
>>> {c: c.isalnum() for c in 'x+1+2'}
{'x': True, '+': False, '1': True, '2': True}
Upvotes: 1