Python3实现字符串单词逆序排列

小石头
小石头
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍如何使用Python3实现字符串中单词的逆序排列,保持单词内部字母顺序不变。通过split和reverse方法,将句子按空格分割后反转列表,再重新拼接为字符串。

本文介绍了利用Python3实现字符串倒序排列的方法,内容包含详细的示例代码,对学习和工作具有参考价值。

问题背景与要求

该问题源自Google测试工程师的一道面试题。

要求设计一个函数,使用任意编程语言实现以下功能:

输入一个句子,将其中所有单词的顺序完全倒排,但每个单词内部的字母顺序保持不变。例如,输入This is a real world,,

期望输出为world real a is this.。

Python实现方案

下面演示如何使用Python语言实现该功能。

假设输入的句子为:

具体实现代码如下。


#!/usr/bin/env python3.4
# -*- coding: utf-8 -*-

#某一段文字
data = "You don't need us to tell you that China's Internet space is booming. With the world's largest Internet user population—686 million as of January 2016—and a long way to go to reach Internet penetration levels of developed countries, China's Internet industry is growing in both scale and influence. And as more and more Chinese users come online, Baidu continues to innovate to meet their changing needs and diverse tastes. We aim to serve the needs of our users and customers with products and solutions that prioritize the user experience and reflect our corporate culture – simple and reliable."

#按照空格分割
strings = data.split()
arr = []

#打印出来
for string in strings:
  arr.append(string)

#将文本倒叙
arr.reverse()
# 按照空格将文本变为字符串
newstring = " ".join(arr)

print(newstring)

运行结果如下:

以上就是本文的全部内容,希望能为读者的学习提供帮助,也欢迎大家继续支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表