python - 如何在 Python 中获取字符的位置?

标签 python string

如何在 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 in s[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]])
Like find() but raise ValueError when the substring is not found.

关于python - 如何在 Python 中获取字符的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2294493/

相关文章:

python - 如果指定用户名,为什么我的 getopts 会失败?

python - beautifulsoup4在mac上使用python3安装和导入

python - 帮助在重新加载或子进程之间进行选择

c# - 查找字符串中的第一个字母字符

python - 如何自定义使用 py.test 生成的 html 报告文件?

python - 解释用于文本分类的随机森林模型

java - 来自给定列表的用户输入,混合了 String 和 Int

c++ - 将 QDate 转换为 Qstring?

Python:字符串不会转换为 float

python - 在 Python 中处理字符串 : Formatting the information in a very specific way