在字符串中查找字符的索引 [英] Finding the Index of a character within a string

查看:86
本文介绍了在字符串中查找字符的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

使用列表很有意义:

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

 animal = l.index["dog"] 

将返回[1],但是我如何用string做同样的事情..

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

 s = "mouse"

 animal_letter = s.index["s"]

它说没有属性.index

it says there is no attribute .index

还有另一种方法可以做到这一点吗?

Is there another way I can do this?

推荐答案

尝试

它返回从0开始的索引(0是字符串的第一个字符)或-1(如果找不到模式).

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

这篇关于在字符串中查找字符的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆