>>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1
使用索引()
>>> 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
def charposition(string, char):
pos = [] #list to store positions for each 'char' in 'string'
for n in range(len(string)):
if string[n] == char:
pos.append(n)
return pos
s = "sentence"
print(charposition(s, 'e'))
#Output: [1, 4, 7]
8 回答
仅为了完整起见,如果您需要在字符串中查找字符的所有位置,您可以执行以下操作:
将返回
[4, 9]
也许你想看一下the documentation来找出两者之间的区别 .
只是为了完成,如果我想在文件名中找到扩展名以便检查它,我需要找到最后的' . ',在这种情况下使用rfind:
在我的情况下,我使用以下,无论完整的文件名是什么:
有两种字符串方法,
find()
和index()
. 两者之间的差异是找不到搜索字符串时发生的情况 .find()
返回-1
和index()
引发ValueError
.使用find()
使用索引()
来自Python手册
和:
字符可能在字符串中出现多次 . 例如,在字符串
sentence
中,e
的位置是1, 4, 7
(因为索引通常从零开始) . 但我发现的是find()
和index()
两个函数都返回一个字符的第一个位置 . 所以,这可以解决这个问题:more_itertools.locate是第三方工具,可查找满足条件的所有项目的指示 .
在这里,我们找到了字母
"i"
的所有索引位置 .“啰嗦”的方式
得到子串,
当字符串包含重复字符时会发生什么?根据我对
index()
的经验,我看到重复你得到相同的索引 .例如:
会回来:
在这种情况下,你可以这样做: