【问题标题】:How to find last letter on word in string with find method?如何使用 find 方法查找字符串中单词的最后一个字母?
【发布时间】:2019-05-12 18:08:41
【问题描述】:

正如标题所说。 我没有从事高项目或其他工作,但这个问题让我很奇怪。

Meri = "Meri: We are class"
Meri_1 = Meri.find('Meri')
print(Meri_1)

我想找到单词“Meri”的第一个和最后一个字母,这意味着 打印 0 和 3。

【问题讨论】:

  • print(Meri_1[0]) print(Meri_1[3]) ?
  • 这只会打印该偏移量上的字母,但我想打印这两个字母的偏移量。

标签: python find letter


【解决方案1】:

试试这个

word = "Gaben"
index = word.index("b")
print(index)    #Output: 2

如果你想反向尝试

word = "Gabe will love Gabe"
last_index = word.rindex("Gabe")
print(last_index)    #Output: 15

【讨论】:

    【解决方案2】:

    由于您知道要查找的最后一个字母的字符串的长度,您可以这样做:

    search_string = "Meri"
    print(Meri.find(search_string) + len(search_string) - 1)
    

    所有这一切都是获取您要查找的字符串的长度,将其添加到字符串开头的索引,然后减去 1 以获得该字符串的最后一个字符。

    使用您拥有的示例,Meri.find(search_string) 将返回 0,当您添加 len(search_string) 时会返回 4,但由于字符串索引为 0,因此您需要减去 1 才能给出正确的索引。

    【讨论】:

    • 谢谢,这样就可以了。我期待 find 的东西,但这给出了相同的结果。
    猜你喜欢
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2014-05-07
    • 2015-10-13
    • 2022-01-13
    相关资源
    最近更新 更多