如何在Python中获取多个相同字符及其在字符串中的位置?

How to get a number of same character and their position in a string in Python?

我有一个字符串、列表和起始位置:

s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX"
l = [0, ""]
start = 0

现在我想提取所有 N 及其在字符串中的位置。到目前为止我尝试过的是:

for i in range(len(s)):
    if s[i] == "N":
        l[0] = i+start
        l[1] = s[i]

但我只得到字符串中的最后一个 "N" 字符。有什么建议吗?

如果您枚举列表,您可以检索所有包含 N:

的索引
    s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX"
    indices = []
    start = 0

    for idx, c in enumerate(s):
        if c == "N":
            indices.append(idx)
    indices 

输出:

[0, 1, 10, 14, 21, 22, 23, 24, 25]

另一种使用索引方法的方法:

indices = []
try:
    start = 0
    while True:
        indices.append(s.index('N',start))
        start = indices[-1]+1
except ValueError: pass

使用 numpy 的解决方案:

from numpy import array,where
print(where(array(list(s))==N))

修复您自己的解决方案:

for i in range(len(s)):
    if s[i] == "N":
        indices.append(i)
        indices.append(s[i])

不需要start,建议不要用list作为变量名。

您可以使用列表理解结合 enumerate() 来获取每个目标字符的索引:

s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX"
positions = [i for i,c in enumerate(s) if c == 'N']
>>> positions
[0, 1, 10, 14, 21, 22, 23, 24, 25]