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

如何使用Python函数提取字符串的第1、第2和最后一个完整单词

原代码的问题在于直接对字符串做下标索引,返回的是对应位置的单个字符,并非按语义拆分的完整单词。
要实现按位置提取完整单词,只需要先将句子按空白符分割为单词列表,再对列表做下标索引即可,Python内置的split()方法可以直接实现该分割逻辑,默认会按任意空白符(空格、制表符等)拆分,同时自动忽略字符串首尾的空白。

调整后完整代码

def first_word(sentence):
    words = sentence.split()
    return words[0]
def second_word(sentence):
    words = sentence.split()
    return words[1]
def last_word(sentence):
    words = sentence.split()
    return words[-1]
  
if __name__ == "__main__":
    sentence = "I want to learn python"
    print(first_word(sentence))
    print(second_word(sentence))
    print(last_word(sentence))

运行输出

I
want
python

拓展说明

  • 如果你的单词分隔符不是普通空白,比如是逗号、斜杠等特殊符号,可以给split()传入指定分隔符参数,例如按逗号拆分写为sentence.split(',')即可。
  • 如果需要兼容句子单词数不足的异常场景,可以在函数中加长度判断,避免索引越界报错,示例如下:
    def first_word(sentence):
        words = sentence.split()
        # 单词数不足时返回空字符串,可根据需求调整默认返回值
        return words[0] if len(words) >= 1 else ''
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:45:08