【问题标题】:how to get what number is the letter in the word? [duplicate]如何得到单词中的字母是什么数字? [复制]
【发布时间】:2017-10-05 14:26:26
【问题描述】:

我有这个程序:

word = input('enter word:')
letter = input('enter letter to find:')

y = word.find(letter)
print(y)

它只打印 0:

enter word:pythop
enter letter to find:p
0
>>> 

那么我怎样才能得到这两个字母“p”的位置,因为它只识别其中一个呢?谢谢

【问题讨论】:

  • 你已经掌握了。 y 是索引。 find() 函数找到第一个匹配项。

标签: python string python-3.x


【解决方案1】:

你明白了!字符串位置 0 是字符串中的第一个位置。

>>> 'pythop'.find('p')
0
>>> 'pythop'.find('y')
1
>>>

【讨论】:

  • 是的...但是那里有两个 p 并且它只识别一个...那我怎样才能同时得到它呢?
【解决方案2】:

你确实需要一个循环。如果您只需要检查单个字母(而不是子字符串),则可以枚举单词的字符:

word = input('enter word:')
letter = input('enter letter to find:')

ys = [i for i, l in enumerate(word) if l == letter]
print(ys)

【讨论】:

    【解决方案3】:

    由于拼写错误更新了我的答案:

    我会这样做:

    word = input('enter word:')
    letter = input('enter letter to find:')
    
    y = [i for i in range(len(word)) if word.startswith(letter, i)]
    print(y)
    

    希望对你有帮助

    【讨论】:

    • 是的..它有帮助..谢谢
    【解决方案4】:

    您可以将 find 用于开始和结束位置。这里是文档字符串:

    find(...)
        S.find(sub [,start [,end]]) -> int
    
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
    
        Return -1 on failure.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-29
      • 2020-01-29
      • 1970-01-01
      • 2014-09-28
      • 2015-11-18
      • 2021-05-23
      • 1970-01-01
      • 2016-05-11
      相关资源
      最近更新 更多