简体   繁体   中英

How to find all positions of a character in a string without using enumerate or regex in Python?

I tried using this:

def charFinder(st,ch):
    for i in range(len(st)):
        if st[i]==ch:
            print(st[i])

charFinder("abc abc abc", "a")

But this only prints the letter at position i, and using st.find(ch) prints only the first occurence. How would I find all occurences using a for loop so that it prints this:

0
4
8

Try this method:

def charFinder(st, ch):
    ch_pos_arr = []
    for i in range(len(st)):
        if st[i]==ch:
            ch_pos_arr.append(i)
    print(ch_pos_arr)

If you want more compact syntax you can use list comprehension:

def charFinder(st, ch)
    print([i for i in range(0, len(st)) if st[i] == ch])

try this:

message = 'i love the way this works'
indexes = {}
for character, index in zip(message, range(len(message))):
       if character in indexes.keys():
              indexes[character] += [index]
       else:
              indexes.update({character: [index]})
print(indexes)

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