简体   繁体   中英

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". but it drops me this error:

IndexError: string index out of range

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. 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

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