There are two string methods for this, find()
and index()
.
(有两种字符串方法, find()
和index()
。)
The difference between the two is what happens when the search string isn't found. (两者之间的区别是找不到搜索字符串时发生的情况。)
find()
returns -1
and index()
raises ValueError
. (find()
返回-1
, index()
引发ValueError
。)
Using find()
(使用find()
)
>>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1
Using 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 in s[start:end]
.
(返回s中找到子字符串sub的最低索引,使得sub完全包含在s[start:end]
。)
Return -1
on failure. (失败时返回-1
。)
Defaults for start and end and interpretation of negative values is the same as for slices. (开始和结束的默认值以及负值的解释与切片的默认值相同。)
And:
(和:)
string.index(s, sub[, start[, end]])
Like find()
but raise ValueError
when the substring is not found.
(与find()
类似,但在找不到子字符串时引发ValueError
。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…