我希望能够在字符串中选择某些字母但需要能够获得多个而不是第一个(Python)。我目前有这个代码:
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")
这可以找到一个字母的位置,但是如果我想找到两个p都不起作用,它只会告诉我第一个字母的位置。所以我真正想知道的是,如果有一些循环我可以通过它来找到字母并将它们设置为两个不同的变量,例如“place”和“place2”,或者我必须在多个不同时间使用相同的东西对于每个单独的起点。
答案 0 :(得分:3)
您可以使用re.finditer()
来获取所有子字符串:
>>> 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()))
答案 1 :(得分:1)
正则表达式是一个强大的工具。但是,使用regexp进行简单的字符串文字搜索会产生相当大的开销。
这是一个简单的替代方案,重复调用str.find
,直到找到所有匹配项:
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