J_man
J_man

Reputation: 61

How to find certain letters in a string when there are multiple?

I want to be able to pick out certain letters in a string but need to be able to get the place of multiple rather then just the first (Python). I currently have this code:

word=apple #just and example
character=input("Take a guess")
if character == "a":
    place=word.find("a")
elif character == "b":
    place=word.find("b")
elif character == "c":
    place=word.find("c")
elif character == "d":
    place=word.find("d")
elif character == "e":
    place=word.find("e")
elif character == "f":
    place=word.find("f")
elif character == "g":
    place=word.find("g")
elif character == "h":
    place=word.find("h")
elif character == "i":
    place=word.find("i")
elif character == "j":
    place=word.find("j")
elif character == "k":
    place=word.find("k")
elif character == "l":
    place=word.find("l")
elif character == "m":
    place=word.find("m")
elif character == "n":
    place=word.find("n")
elif character == "o":
    place=word.find("o")
elif character == "p":
    place=word.find("p")
elif character == "q":
    place=word.find("q")
elif character == "r":
    place=word.find("r")
elif character == "s":
    place=word.find("s")
elif character == "t":
    place=word.find("t")
elif character == "u":
    place=word.find("u")
elif character == "v":
    place=word.find("v")
elif character == "x":
    place=word.find("w")
elif character == "w":
    place=word.find("x")
elif character == "y":
    place=word.find("y")
else:
    place=word.find("z")

This works to find the place of one letter, but if I wanted to find both p's it wouldn't work, it'd only tell me the position of the first. So what I'm really wondering is if there is some loop I can put it through to find the letters and set them as two different variables such as "place" and "place2" or do I have to have this same thing multiple different times for each separate starting point.

Upvotes: 3

Views: 491

Answers (2)

VPfB
VPfB

Reputation: 17352

Regular expressions are a powerful tool. However, there is a considerable overhead in using regexps for a trivial string literal search.

Here is a simple alternative repeatedly calling str.find until all occurrences are found:

def findall(mainstring, substring):
    pos = -1
    while True:
        pos = mainstring.find(substring, pos+1)
        if pos == -1: 
            break
        yield pos 

for occurence in findall("apple", "p"):
    print(occurence)
# prints: 1 2

Upvotes: 1

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52203

You can use re.finditer() to get all occurrences of the substring:

 >>> import re

 >>> word = "apple" #just and example
 >>> character = input("Take a guess: ")
 >>> for occurrence in re.finditer(character, word):
 ...     print('character: {}, {}'.format(character, occurrence.start())) 

Upvotes: 3

Related Questions