You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中实现仅显示'ing'最后一次匹配位置的问题

解决只显示'ing'最后一次出现位置的问题

嘿,我懂你的需求啦——你现在的代码会把所有找到的'ing'位置都打印出来,但你只想要最后一次出现的那个位置对吧?咱们来一步步搞定这个问题。

最简单的方法:用rfind()直接定位最后一次出现的位置

Python字符串自带了一个超实用的方法rfind(),它专门用来查找子串最后一次出现的起始索引,找不到就返回-1,完美匹配你的需求!

修改后的代码如下:

userinput = input('Enter a word: ')
last_ing_index = userinput.rfind('ing')
if last_ing_index == -1:
    print('-1')
else:
    # 因为你需要从1开始计数的位置,所以加1
    print('ing found at', last_ing_index + 1)

测试效果:

  • 输入sing,输出2,符合预期;
  • 输入singing,输出5,正好是最后一个'ing'的起始位置(从1计数)。

如果想保留循环思路,怎么调整?

如果你还是想用原来的循环逻辑,那可以改成只记录最后一次找到的位置,等循环结束后再统一打印,而不是每次找到就输出:

userinput = input('Enter a word: ')
current_pos = 0
last_ing_pos = -1  # 初始化最后位置为-1(表示未找到)

while current_pos < len(userinput):
    current_pos = userinput.find('ing', current_pos)
    if current_pos == -1:
        break
    # 更新最后位置为当前找到的索引
    last_ing_pos = current_pos
    # 移动指针,避免重复查找同一个'ing'
    current_pos += 3

# 循环结束后统一处理输出
if last_ing_pos == -1:
    print('-1')
else:
    print('ing found at', last_ing_pos + 1)

这个思路就是每次找到'ing'时,把当前位置存到last_ing_pos里,循环走完后,last_ing_pos就会保留最后一次出现的索引,最后再判断输出即可。

内容的提问来源于stack exchange,提问作者oryh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:43:17