简体   繁体   English

在字符串中查找字符的索引

[英]Finding the Index of a character within a string

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. 这可能是措辞不正确,因为我是一个初学者,但是如果我有字符串,该如何找到某个字符索引,就像使用列表中的.index一样。

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 . 将返回[1],但是我如何使用string做同样的事情。 . .

 s = "mouse"

 animal_letter = s.index["s"]

it says there is no attribute .index 它说没有属性.index

Is there another way I can do this? 我还有其他方法可以做到这一点吗?

Try the string.find method. 尝试使用string.find方法。

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. 它返回从0开始的索引(0是字符串的第一个字符)或-1(如果找不到模式)。

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

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

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