我正在尝试使用非常基本的技能集在 python 字符串中查找字符的所有索引号。例如,如果我有字符串“Apples are fully awesome”,并且我想找到字符串中 'a' 的位置。我的理想输出是:
0
7
14
19
Run Code Online (Sandbox Code Playgroud)
这些是字符串中出现“a”的所有位置(我认为)
这是我到目前为止的代码:
sentence = input("Input a string: ")
for ch in sentence:
x = sentence.find('o')
print(x)
Run Code Online (Sandbox Code Playgroud)
在这里,我正在寻找 'o' 而不是 a。我的想法是,对于字符串中的每个字符,find 函数都会返回 'o' 的位置。因为我不知道输入字符串需要多长时间,所以我使用了 for 循环。我能够找到并打印出“o”的第一个实例,但不是全部。我该怎么办?提前致谢!