简体   繁体   English

for 循环如何处理 python 中的字符串值?

[英]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.第一个代码给出错误“TypeError:'str' object 不能被解释为整数”,而第二个代码工作正常。 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.我认为for循环计数字符串如下:“apple”中的for变量等同于range(5)中的变量,0链接到a,1链接到p,2链接到p,3链接到l,4链接到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.我认为for循环计数字符串如下:“apple”中的for变量等同于range(5)中的变量,0链接到a,1链接到p,2链接到p,3链接到l,4链接到e。 Is that not the case?不是这样吗?

No, for var in "apple" works as 'a', 'p', 'p', 'l', 'e'.不, for var in "apple"可以用作“a”、“p”、“p”、“l”、“e”。 So your code with letter = s[n:var+1] won't work.因此,您的带有letter = s[n:var+1]的代码将不起作用。

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() :如果您还想要一个数字(例如 0、'a'、1、'p'、2、'p' 等),请使用enumerate()

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

0 a
1 p
2 p
3 l
4 e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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