简体   繁体   English

Python中的字符串索引超出范围

[英]string index out of range in Python

I want to find how many times an character repeated in a word for example: how many times the 'l' repeated in the "Hello".我想找出一个字符在一个单词中重复了多少次,例如:“你好”中“l”重复了多少次。 but it drops me this error:但它给我带来了这个错误:

IndexError: string index out of range IndexError:字符串索引超出范围

And my code:还有我的代码:

def fin(x,lst):
   if x == '':
      return 0
   if lst[0] == x:
      return 1+ fin(x,lst[1:])
   else:
      return fin(x,lst[1:])

There are pre-written functions in python to do this for you. python 中有预先编写的函数可以为您执行此操作。 But if you're doing this for the sake of education...但如果你这样做是为了教育......

You have the wrong stop condition, you should be checking if the lst is empty, not x您有错误的停止条件,您应该检查lst是否为空,而不是x

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

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