如何在python中获取字符串中字符的位置?
ask by user244470 translate from so There are two string methods for this, find()
and index()
.
(有两种字符串方法, find()
和index()
。)
(两者之间的区别是找不到搜索字符串时发生的情况。)
find()
returns -1
and index()
raises ValueError
. (find()
返回-1
, index()
引发ValueError
。)
find()
(使用find()
) >>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1
index()
(使用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
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]
.(返回s中找到子字符串sub的最低索引,使得sub完全包含在
s[start:end]
。)Return-1
on failure.(失败时返回
Defaults for start and end and interpretation of negative values is the same as for slices.-1
。)(开始和结束的默认值以及负值的解释与切片的默认值相同。)
And:
(和:)
string.index(s, sub[, start[, end]])
Likefind()
but raiseValueError
when the substring is not found.(与
find()
类似,但在找不到子字符串时引发ValueError
。)