简体   繁体   中英

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

I have a string, list and start position:

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

Now I want to extract all the N's and their positions in the string. What I have tried so far is:

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

But I only get the last "N" character from the string. Any suggestions?

You can use a list comprehension combined with enumerate() to get the indices of each target character:

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

If you enumerate the list, you can retrieve all the indices where there is a N :

    s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX"
    indices = []
    start = 0

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

output:

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

Another way using the index method:

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

A solution using numpy:

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

fixing your own solution:

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

You don't need start, and I suggest you don't use list as a variable name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM