Print all the "a" of a string on python

Question:

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"

Asked By: Martí Xuclà

||

Answers:

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)
Answered By: Deepak Tripathi

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)

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')
Answered By: cards
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.