【发布时间】:2020-08-18 02:26:23
【问题描述】:
我知道我可以为此使用 .count() 函数,但我尝试使用 for 循环来执行此操作,并且在第 6 行中不断收到编译错误。有人看到这段代码有什么问题吗?为什么它不会给出相同的输出?提前致谢!
def count_hi(string):
# Create an empty list to add to
num_hi = []
# for every index in string , if the character is h and the next is i,
# add element to list
for index in string:
if string[index] == 'h' AND string[index + 1] == 'i':
num_hi.append('hi found')
return len(num_hi) # return length of list
【问题讨论】:
-
python 区分大小写。使用
and而不是AND -
我发现了两个问题。
AND应该是小写的and。而你的 for 循环是循环遍历元素,而不是索引,所以index是一个字符,例如'h'。代替for index in string,使用for index in range(len(string))
标签: python string loops for-loop