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


当前回答

string.find(character)  
string.index(character)  

也许您想查看一下文档,以找出两者之间的区别。

其他回答

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

“冗长”的方式

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

要得到substring,

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

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

例如:

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

为了完整起见,如果你需要找到字符串中某个字符的所有位置,你可以这样做:

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

这将打印:[4,9]

一个字符可能在字符串中出现多次。例如,在一个字符串句子中,e的位置是1,4,7(因为索引通常从0开始)。但我发现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]

使用numpy快速访问所有索引的解决方案:

string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')