如何实现控制台输入语句的首尾单词互换功能?
实现控制台输入语句首尾单词互换功能
核心思路
- 读取控制台输入的完整语句
- 将语句按空白字符拆分为单词列表,自动处理多个连续空格的情况
- 若列表长度大于1,交换第一个和最后一个元素;若只有单个单词,直接返回原句
- 将处理后的列表重新拼接为字符串输出
基础实现代码(Python)
# 读取控制台输入 input_str = input("请输入需要处理的语句:") # 按空白分割成单词列表 words = input_str.split() # 处理边界情况:仅单个单词时无需交换 if len(words) > 1: # 交换首尾单词 words[0], words[-1] = words[-1], words[0] # 拼接成新字符串并输出 output_str = ' '.join(words) print(output_str)
针对标点的优化处理
如果需要像示例那样,把末尾单词附带的标点保留在句子结尾(比如输入London is the Capital of UK.,输出UK is the Capital of London.),可以增加标点分离逻辑:
import string input_str = input("请输入需要处理的语句:") words = input_str.split() if len(words) > 1: # 提取第一个单词的前置标点(如果存在) first_word = words[0] first_punct = '' while first_word and first_word[0] in string.punctuation: first_punct += first_word[0] first_word = first_word[1:] # 提取最后一个单词的末尾标点 last_word = words[-1] last_punct = '' while last_word and last_word[-1] in string.punctuation: last_punct = last_word[-1] + last_punct last_word = last_word[:-1] # 交换处理后的纯单词,重新拼接标点 words[0] = first_punct + last_word words[-1] = first_word + last_punct output_str = ' '.join(words) print(output_str)
测试示例
输入:
London is the Capital of UK.
输出:
UK is the Capital of London.
内容的提问来源于stack exchange,提问作者Андрій Гула
相关产品推荐
相关产品推荐

