Finding the Index of a character within a string

帅比萌擦擦* 提交于 2021-02-08 08:30:30

问题


This may be worded incorrectly because I'm a wee beginner, but if I have a string how to I find a certain characters index like you can with the .index thing in lists.

With a list it makes sense:

 l = ["cat", "dog", "mouse"]

 animal = l.index["dog"] 

will return [1], but how do I do the same thing with strings . . .

 s = "mouse"

 animal_letter = s.index["s"]

it says there is no attribute .index

Is there another way I can do this?


回答1:


Try the string.find method.

s = "mouse"
animal_letter = s.find('s')
print animal_letter

It returns the 0-based index (0 is the first character of the string) or -1 if the pattern is not found.

>>> "hello".find('h')
0
>>> "hello".find('o')
4
>>> "hello".find("darkside")
-1


来源:https://stackoverflow.com/questions/19894329/finding-the-index-of-a-character-within-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!