1

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?

4

1 回答 1

4

试试string.find方法。

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

它返回从 0 开始的索引(0 是字符串的第一个字符),如果未找到该模式,则返回 -1。

>>> "hello".find('h')
0
>>> "hello".find('o')
4
>>> "hello".find("darkside")
-1
于 2013-11-10T19:53:45.840 回答