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

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

本文介绍如何使用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 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。