如何在Python中获取字符的位置? [英] How to get the position of a character in Python?

查看:103
本文介绍了如何在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.startend 的默认值,负值的解释与切片相同.

还有:

<块引用>

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

这篇关于如何在Python中获取字符的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆