开发者

Python: How to get the Index of a string

开发者 https://www.devze.com 2023-02-22 01:49 出处:网络
How can I write a function that retu开发者_如何学Pythonrns the index of a single character in a string without using the index method a.k.astring.index(\'some random character\')?Another variant that

How can I write a function that retu开发者_如何学Pythonrns the index of a single character in a string without using the index method a.k.a string.index('some random character')?


Another variant that works with multiple occurrences of char in string.

def idx(string, char):
  for key, x in enumerate(string):
    if x == char:
      print key


it's a school task?

def ind(the_string, the_char):
   i = 0
   for a_char in the_string:
       if a_char == the_char: return i
       i += 1
   return -1


index() is the same thing as find() except for the error when the string isn't found.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号