【问题标题】:finding the index of the same letter in a string在字符串中查找相同字母的索引
【发布时间】:2021-06-02 20:14:28
【问题描述】:

目前正在合作

def order(word):
  for each in word:
    print str(word.index(each))+ ": "+each

如果我运行order("Ranger"),代码会按我的意愿运行,它会为我提供:

0: R
1: a
2: n
....and so on until "5: r"

但是如果我输入任何带有重复字母的单词,例如“hall”或“silicon”,我会得到该单词第一次迭代的位置值,例如:

order("Hall")
0: H
1: a
2: l
2: l

如何让函数返回以下内容?

0: H
1: a
2: l
3: l

【问题讨论】:

  • order("ranger") - 'R' != 'r' 也会有类似的“错误”输出。您的问题是您没有指定在文本中查找字符的起始位置,因此它会找到第一个实例。
  • index() 仅返回最低索引(尽管您可以指定开始参数),它还会为每个不必要的字母迭代相同的单词一次,因此在 enumerate(word) 上使用 for 循环.

标签: python jython


【解决方案1】:

str.index() 只返回子字符串的最低索引。

您可以只enumerate 一个字符串用于您的目的:

def order(word):
    for index, letter in enumerate(word):
        print('{}: {}'.format(index,letter))

另外,请考虑使用 python 3.x。

【讨论】:

    【解决方案2】:

    由于您将其标记为 Python,因此这里是 Python 实现。

    def order(word):
      for i in range(len(word)):
        print(i+1, ":", word[i])
    order("hall")
    

    我基本上是在遍历单词的长度并打印出该位置的字符。在您的情况下, str.index() 打印出第一次出现的字符。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      相关资源
      最近更新 更多