0

I'm trying to print all the "a" or other characters from an input string. I'm trying it with the .find() function but just print one position of the characters. How do I print all the positions where is an specific character like "a"

  • 2
    Does this answer your question? [How to find all occurrences of a substring?](https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring) – luk2302 Oct 20 '22 at 10:16

3 Answers3

1

You can use find with while loop

a = "aabababaa"
k = 0
while True:
    k = a.find("a", k) # This is saying to start from where you left
    if k == -1:
        break
    k += 1
    print(k)
Deepak Tripathi
  • 3,175
  • 1
  • 8
  • 21
1

This is also possible with much less amount of code if you don't care where you want to start.

a = "aabababaa"

for i, c in enumerate(a): # i = Index, c = Character. Using the Enumerate()
  if ("a" in c):
    print(i)
0

Some first-get-all-matches-and-then-print versions:

With a list comprehension:

s = "aslkbasaaa"

CHAR = "a"
pos = [i for i, char in enumerate(s) if char == CHAR]
print(*pos, sep='\n')

or with itertools and composition of functions

from itertools import compress

s = "aslkbasaaa"

CHAR = "a"
pos = compress(range(len(s)), map(CHAR.__eq__, s))
print(*pos, sep='\n')
cards
  • 3,936
  • 1
  • 7
  • 25