本文介绍了如何在Python中获取字符的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在python中获取字符串中字符的位置?
解决方案
为此有两种字符串方法,find()
和 index()
.两者之间的区别在于未找到搜索字符串时会发生什么.find()
返回 -1
并且 index()
引发 ValueError
.
使用find()
.失败时返回 -1
.start 和 end 的默认值,负值的解释与切片相同.还有:
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
And:
这篇关于如何在Python中获取字符的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!