【问题标题】:basic question about finding all indices of an occurrences in a string [duplicate]关于查找字符串中出现的所有索引的基本问题[重复]
【发布时间】:2020-01-02 08:11:31
【问题描述】:

我刚开始学习如何用 python 编码,我需要一些关于我编写的简单代码的反馈

目标:查找并打印字符串中“e”的所有索引

我写的代码

sentence = "celebrate"

for i in sentence:
    if i == "e":
        indexed_sentence = sentence.index("e")
        print(indexed_sentence)

我想打印代码 1,3,8

【问题讨论】:

标签: python


【解决方案1】:

.index 方法将返回您正在搜索的字符第一次 出现的索引。这意味着您将始终看到 1 的代码。更好的方法是按照@Rakesh 的建议使用内置函数enumerate

sentence = "celebrate"

for ix, c in enumerate(sentence):
    if c=="e":
        print(ix)

【讨论】:

  • thnx,现在我可以继续了。
【解决方案2】:

您正在循环字符串并正确匹配所需的字符。当您找到匹配项时,您只是在运行indexed_sentence = sentence.index("e"),它每次都会给出相同的答案。您可以使用enumerate 修改循环以便知道匹配的索引。

sentence = "celebrate"

for i, c in enumerate(sentence):
    if c == "e":
        print(i)

【讨论】:

  • thnx,现在我可以继续了。
猜你喜欢
  • 2012-11-15
  • 2016-05-13
  • 2019-12-10
  • 1970-01-01
  • 2021-10-23
  • 2016-12-02
  • 2011-10-22
  • 2012-10-12
相关资源
最近更新 更多