Reputation: 13
I'm trying to iterate a string to do an if statement to check if its uppercase or not for example:
s="abcd"
for x in s:
if s[x].isupper():
print(s[x])
However this doesn't work. But if I use a while
loop, it works:
i=0
while i < len(s):
if s[i].isupper():
print(s[i])
I just want to know if the same while
loop can be made with a for
loop
Upvotes: 1
Views: 41
Reputation: 477190
That's because a for
loop iterates over the characters. So x
in your for
loop is a character, not an index:
s="abcd"
for x in s:
if x.isupper():
print(x)
Should work. Python sees strings as an ordered collection of characters. A for
loop over a collection usually iterates over its elements (the keys in case of a dictionary).
Upvotes: 2