如何在Python中获取字符的位置? [英] How to get the position of a character in Python?
问题描述
如何在python中获取字符串中字符的位置?
为此有两种字符串方法,find()
和 index()
.两者之间的区别在于未找到搜索字符串时会发生什么.find()
返回 -1
并且 index()
引发 ValueError
.
使用find()
<预><代码>>>>myString = '字符的位置'>>>myString.find('s')2>>>myString.find('x')-1<小时>
使用index()
<预><代码>>>>myString = '字符的位置'>>>myString.index('s')2>>>myString.index('x')回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中值错误:未找到子字符串<小时>
来自 Python 手册
<块引用>string.find(s, sub[, start[, end]])
返回 s 中的最低索引,其中找到子字符串 sub 使得 sub 完全包含在 s[start:end]代码>.失败时返回
-1
.start 和 end 的默认值,负值的解释与切片相同.
还有:
<块引用>string.index(s, sub[, start[, end]])
与 find()
类似,但在未找到子字符串时引发 ValueError
.
How can I get the position of a character inside a string in python?
There are two string methods for this, find()
and index()
. The difference between the two is what happens when the search string isn't found. find()
returns -1
and index()
raises ValueError
.
Using find()
>>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1
Using index()
>>> myString = 'Position of a character'
>>> myString.index('s')
2
>>> myString.index('x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
From the Python manual
string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained ins[start:end]
. Return-1
on failure. Defaults for start and end and interpretation of negative values is the same as for slices.
And:
string.index(s, sub[, start[, end]])
Likefind()
but raiseValueError
when the substring is not found.
这篇关于如何在Python中获取字符的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!