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

使用.find()函数循环获取句子最后单词遇异常求排查及正确方案

问题分析与解决方案

失效原因

你的代码存在两个核心问题:

  • 循环条件逻辑错误:用index < len(sentence)作为循环终止条件,但每次循环中sentence会被截断缩短,而index持续递增。当index增长到大于当前sentence的长度时,循环会提前终止,此时sentence中仍包含空格,无法得到最后一个单词。
  • 无意义的冗余循环:当sentence只剩最后一个单词时,find(" ")返回-1,执行sentence = sentence[substring+1:]等价于保留原字符串,但index仍会继续递增直到满足退出条件,这部分循环完全无效。

不使用split()的正确实现

方法一:循环查找直到无空格

通过循环持续查找空格,每次截断空格前的部分,直到找不到空格为止:

sentence = "please write a program which keeps asking the user for words"
while True:
    space_pos = sentence.find(" ")
    if space_pos == -1:
        break
    sentence = sentence[space_pos + 1:]
print(sentence)

方法二:用rfind()直接定位最后一个空格

rfind()方法会直接返回最后一个空格的索引,一步到位获取最后一个单词,效率更高:

sentence = "please write a program which keeps asking the user for words"
last_space_pos = sentence.rfind(" ")
last_word = sentence[last_space_pos + 1:] if last_space_pos != -1 else sentence
print(last_word)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 16:45:01