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

如何实现提取字符串首词、次词及末词的Python函数?

问题与解决方案

需求描述

给定一个字符串,需编写三个独立函数:

  • first_word:输出字符串的第一个单词
  • second_word:输出字符串的第二个单词
  • last_word:输出字符串的最后一个单词

注:若字符串仅有2个单词,second_word与last_word的输出需一致。

示例代码:

sentence = "once upon a time there was a programmer"

print(first_word(sentence)) # once
print(second_word(sentence)) # upon
print(last_word(sentence)) # programmer

已尝试代码

def first_word(str):
       space = str.find(' ')
       return(str[0:space])

sentence = "once upon a time there was a programmer"
print(first_word(sentence))

输出:once

问题

不清楚如何实现second_word和last_word函数,能否复用first_word函数的逻辑?请说明实现思路。


解决方案

实现思路

两种方案供选择:

  1. 推荐:分割为单词列表:用str.split()方法把字符串转成单词列表,该方法会自动忽略首尾空格、连续空格,直接通过索引取对应单词,逻辑简单不易出错。
  2. 复用原始逻辑:基于find/rfind找空格位置的思路扩展——second_word可以先定位第一个空格,取后续子串再调用first_word;last_word从后往前找最后一个空格,取空格后的子串。

代码实现

方案一:基于单词列表(简洁可靠)

def first_word(s):
    words = s.split()
    return words[0] if words else ""

def second_word(s):
    words = s.split()
    # 单词数>=2取第二个,只有1个单词取自身,空串返回空
    return words[1] if len(words) >=2 else (words[0] if words else "")

def last_word(s):
    words = s.split()
    return words[-1] if words else ""

# 测试示例
sentence = "once upon a time there was a programmer"
print(first_word(sentence))  # once
print(second_word(sentence)) # upon
print(last_word(sentence))   # programmer

# 测试2个单词的场景
short_sentence = "hello world"
print(second_word(short_sentence)) # world
print(last_word(short_sentence))   # world

方案二:复用first_word原始逻辑

def first_word(s):
    space_idx = s.find(' ')
    # 处理无空格(仅一个单词)的情况
    return s[:space_idx] if space_idx != -1 else s

def second_word(s):
    first_space = s.find(' ')
    if first_space == -1:
        return s  # 只有一个单词时返回自身
    # 取第一个空格后的子串,先去掉多余空格再调用first_word
    sub_str = s[first_space+1:].strip()
    return first_word(sub_str)

def last_word(s):
    last_space = s.rfind(' ')
    # 处理无空格的情况
    return s[last_space+1:] if last_space != -1 else s

# 测试
sentence = "once upon a time there was a programmer"
print(first_word(sentence))  # once
print(second_word(sentence)) # upon
print(last_word(sentence))   # programmer

short_sentence = "hello world"
print(second_word(short_sentence)) # world
print(last_word(short_sentence))   # world

说明

  • 方案一的split()是Python处理单词分割的常规操作,能覆盖各种空格异常场景,代码可读性高。
  • 方案二更贴近你最初的实现思路,适合理解字符串切片的底层逻辑,但需要额外处理空格后的冗余空格和边界情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:54:26