如何在Python中获取角色的位置?

问题描述 投票:455回答:8

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

python string
8个回答
601
投票

有两种字符串方法,find()index()。两者之间的区别是找不到搜索字符串时发生的情况。 find()返回-1index()引发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]]) 返回s中找到子字符串sub的最低索引,使得sub完全包含在s[start:end]中。失败时返回-1。开始和结束的默认值以及负值的解释与切片的默认值相同。

和:

string.index(s, sub[, start[, end]])find()一样,但是当找不到子串时会提升ValueError


97
投票

只是为了完整起见,如果您需要查找字符串中字符的所有位置,您可以执行以下操作:

s = 'shak#spea#e'
c = '#'
print [pos for pos, char in enumerate(s) if char == c]

这将返回[4, 9]


46
投票
>>> s="mystring"
>>> s.index("r")
4
>>> s.find("r")
4

“啰嗦”的方式

>>> for i,c in enumerate(s):
...   if "r"==c: print i
...
4

得到子串,

>>> s="mystring"
>>> s[4:10]
'ring'

15
投票

当字符串包含重复字符时会发生什么?根据我对index()的经验,我看到重复你得到相同的索引。

例如:

s = 'abccde'
for c in s:
    print('%s, %d' % (c, s.index(c)))

会回来:

a, 0
b, 1
c, 2
c, 2
d, 4

在这种情况下,你可以这样做:

for i, character in enumerate(my_string):
   # i is the position of the character in the string

14
投票

只是为了完成,如果我想在文件名中找到扩展名来检查它,我需要找到最后的'。',在这种情况下使用rfind:

path = 'toto.titi.tata..xls'
path.find('.')
4
path.rfind('.')
15

在我的情况下,我使用以下,无论完整的文件名是什么,它都适用:

filename_without_extension = complete_name[:complete_name.rfind('.')]

11
投票
string.find(character)  
string.index(character)  

也许你想看看the documentation,看看两者之间的区别是什么。


3
投票

字符可能会在字符串中多次出现。例如,在字符串sentence中,e的位置是1, 4, 7(因为索引通常从零开始)。但我发现的是find()index()这两个函数都返回一个角色的第一个位置。所以,这可以解决这个问题:

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]

0
投票

qazxsw poi是第三方工具,可查找满足条件的所有项目索引。

在这里,我们找到字母more_itertools.locate的所有索引位置。

"i"
© www.soinside.com 2019 - 2024. All rights reserved.