这可能是措辞不正确,因为我是一个初学者,但是如果我有字符串,该如何找到某个字符索引,就像使用列表中的.index一样。
使用列表很有意义:
l = ["cat", "dog", "mouse"]
animal = l.index["dog"]
将返回[1],但是我如何使用string做同样的事情。。。
s = "mouse"
animal_letter = s.index["s"]
它说没有属性.index
我还有其他方法可以做到这一点吗?
尝试使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句