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

Python无外部函数实现:交换字符串中最长与最短单词(保留标点)

Python实现字符串指定单词交换(保留标点)

解决思路

直接用replace()做双向替换会互相冲突——比如先把"to"换成"introduction",再把"introduction"换成"to",刚替换的内容会被二次修改,等于白忙活。得根据需求分两种场景处理:


场景1:替换所有最长/最短单词

如果要把所有的最短单词(比如示例里的"to")和所有的最长单词(比如"introduction")互相替换,用临时标记法就能搞定:

# 读取文本(实际可改为从文件读取:with open('your_file.txt', 'r') as f: line = f.read())
line = "Welcome to your personal dashboard, where you can find an introduction to how GitHub works, tools to help you build software, and help merging your first lines of code."

# 提取纯单词列表,用于找最长/最短
word_units = line.split()
pure_words = [unit.rstrip(',.') for unit in word_units]

# 确定最长和最短单词
longest_word = max(pure_words, key=len)
shortest_word = min(pure_words, key=len)

# 用临时标记避免替换冲突
temp_tag = "___TEMP_MARK___"
# 第一步:把所有最短单词换成临时标记
temp_line = line.replace(shortest_word, temp_tag)
# 第二步:把所有最长单词换成最短单词
temp_line = temp_line.replace(longest_word, shortest_word)
# 第三步:把临时标记换成最长单词
final_line = temp_line.replace(temp_tag, longest_word)

print(final_line)

这段代码会把所有"to"换成"introduction",所有"introduction"换成"to",输出结果里开头的"Welcome to"会变成"Welcome introduction"。


场景2:交换特定的两个单词(匹配你的期望结果)

如果只是要把唯一的最长单词和某一个最短单词(比如最后一次出现的"to")交换位置,需要先定位两个单词的位置,再交换原始的带标点单元:

line = "Welcome to your personal dashboard, where you can find an introduction to how GitHub works, tools to help you build software, and help merging your first lines of code."

# 拆分带标点的单词单元,同时记录纯文本和原始内容
word_info = []
for unit in line.split():
    pure_word = unit.rstrip(',.')  # 手动去除末尾标点,不用外部库
    word_info.append( (pure_word, unit) )

# 找到最长单词的索引
longest_idx = 0
max_length = len(word_info[0][0])
for i, (pure, _) in enumerate(word_info):
    if len(pure) > max_length:
        max_length = len(pure)
        longest_idx = i

# 找到最后一个最短单词的索引
shortest_idx = 0
min_length = len(word_info[0][0])
for i, (pure, _) in enumerate(word_info):
    if len(pure) <= min_length:
        min_length = len(pure)
        shortest_idx = i

# 交换两个位置的单词单元
word_info[longest_idx], word_info[shortest_idx] = word_info[shortest_idx], word_info[longest_idx]

# 重新拼接成最终字符串
final_line = ' '.join([unit for (pure, unit) in word_info])
print(final_line)

运行后输出和你期望的完全一致:

"Welcome to your personal dashboard, where you can find an to to how GitHub works, tools introduction help you build software, and help merging your first lines of code."


关键说明

  • 手动用rstrip(',.')去除单词末尾标点,避免导入正则等外部工具,符合要求。
  • 场景2通过记录每个单词的原始带标点形式,交换后能完整保留原有的标点位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 20:55:17