如何在 Python 中获取字符在字符串中的位置?
最佳答案
有两个字符串方法,find()
和 index()
。两者之间的区别在于找不到搜索字符串时会发生什么。 find()
返回 -1
并且 index()
引发 ValueError
。
使用 find()
>>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1
使用 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
来自 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.
还有:
string.index(s, sub[, start[, end]])
Likefind()
but raiseValueError
when the substring is not found.
关于python - 如何在 Python 中获取字符的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2294493/