I want to check a string's character whether it is alphabet or numeric, uppercase or lowercase but character by character in Python. Can anybody help me with this? Tell me if any module is to be imported. An example code working on the cs50 IDE is more helpful. Please reply as soon as possible.
1 Answer
There are methods like isalpha
on strings. To test single characters, pick that character first, like str[i].isalpha()
. As strings are iterables, you can also do that with list comprehensions, like
my_string = "abCD12EFgh34"
my_alpha = [c.isalpha() for c in my_string]
my_upper = [c.isupper() for c in my_string]
my_digit = [c.isdigit() for c in my_string]
which would result in lists full of True
/False
. Completely depends on what you want to do. Maybe a simple for-loop like for c in my_string:
would be the way to go, or a for index in range(len(my_string)):
if that index is relevant in any way.