简体   繁体   中英

How do for loops work with string values in python?

I am confused about working for loops with strings.

s=input("enter a lowercase word")

counter = 0

n=0

for var in s:
    letter = s[n:var+1]

if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':

    counter += 1

n += 1 

print('Number of vowels:', counter)

  iteration = 0

count = 0

   while iteration < 5:

      for letter in "hello, world":

      count += 1

   print("Iteration " + str(iteration) + "; count is: " + str(count))

   iteration += 1

The 1st code gives an error "TypeError: 'str' object cannot be interpreted as an integer" whearas the 2nd code works fine. I thought the for loop counted string as follows: for variable in "apple" was equivalent to for variable in range(5) and 0 was linked to a, 1 to p, 2 to p, 3 to l and 4 to e. Is that not the case?

I thought the for loop counted string as follows: for variable in "apple" was equivalent to for variable in range(5) and 0 was linked to a, 1 to p, 2 to p, 3 to l and 4 to e. Is that not the case?

No, for var in "apple" works as 'a', 'p', 'p', 'l', 'e'. So your code with letter = s[n:var+1] won't work.

s=input("enter a lowercase word")

counter = 0

for letter in s:
    if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
        counter += 1

print('Number of vowels:', counter)

If you also want a number (eg 0, 'a', 1, 'p', 2, 'p', etc.), use enumerate() :

for idx, var in enumerate("apple"):
    print(idx, var)

0 a
1 p
2 p
3 l
4 e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM