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


当前回答

more_itertools。Locate是一个第三方工具,用于查找满足条件的项目的所有索引。

这里我们找到了字母“i”的所有索引位置。

鉴于

import more_itertools as mit


text = "supercalifragilisticexpialidocious"
search = lambda x: x == "i"

Code

list(mit.locate(text, search))
# [8, 13, 15, 18, 23, 26, 30]

其他回答

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

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

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

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

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

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

这将打印:[4,9]

>>> 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'

我发现的大多数方法都是指查找字符串中的第一个子字符串。要找到所有的子字符串,您需要处理。

例如:

定义字符串

vars = 'iloveyoutosimidaandilikeyou'

定义子字符串

key = 'you'

定义一个函数,该函数可以找到字符串中所有子字符串的位置

def find_all_loc(vars, key):

    pos = []
    start = 0
    end = len(vars)

    while True: 
        loc = vars.find(key, start, end)
        if  loc is -1:
            break
        else:
            pos.append(loc)
            start = loc + len(key)
            
    return pos

pos = find_all_loc(vars, key)

print(pos)
[5, 24]