Python字符串处理实现单词反转
作者:qq_21089969 时间:2021-01-30 19:19:01
Python字符串处理学习中,有一道简单但很经典的题目,按照单词对字符串进行反转,并对原始空格进行保留:
如:‘ I love China! ‘
转化为:‘ China! love I ‘
两种解决方案:
方案1:从前往后对字符串进行遍历,如果第一个就是空格,直接跳过,直到第一个不是空格的字符,如果是单独的字母,同样跳过,否则的话,将该单词进行反转,再往后遍历,最后使用reserve方法,让整个字符串从后往前打印。
方案2:直接使用re(正则化)包进行反转
代码如下:
import re
def reserve(str_list, start, end):
while start <= end:
str_list[start], str_list[end] = str_list[end], str_list[start]
end -= 1
start += 1
str = ' I love china! '
str_list = list(str)
print(str_list)
i = 0
print(len(str_list))
# 从前往后遍历list,如果碰到空格,就调用反转函数,不考虑单个字符情况
while i < len(str_list):
if str_list[i] != ' ':
start = i
end = start + 1
print(end)
while (end < len(str_list)) and (str_list[end]!=' '):
end += 1
if end - start > 1:
reserve(str_list, start, end-1)
i = end
else:
i = end
else:
i += 1
print(str_list)
str_list.reverse()
print(''.join(str_list))
# 采用正则表达式操作
str_re = re.split(r'(\s+)',str)
str_re.reverse()
str_re = ''.join(str_re)
print(str_re)
标签:Python,单词反转
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python 列表理解及使用方法
2023-08-29 06:55:02
使用 Python 实现微信群友统计器的思路详解
2022-02-04 23:38:08
![](https://img.aspxhome.com/file/2023/6/81606_0s.jpg)
Python在不同场景合并多个Excel的方法
2021-11-03 02:52:00
![](https://img.aspxhome.com/file/2023/7/107867_0s.webp)
几行Python代码爬取3000+上市公司的信息
2022-11-17 22:04:09
![](https://img.aspxhome.com/file/2023/3/107973_0s.png)
全面了解python中的类,对象,方法,属性
2021-10-07 10:54:50
TensorFlow平台下Python实现神经网络
2023-10-11 22:31:31
![](https://img.aspxhome.com/file/2023/1/86411_0s.png)
Python基础之高级变量类型实例详解
2021-11-09 11:07:40
![](https://img.aspxhome.com/file/2023/0/112010_0s.png)
Swoole webSocket消息服务系统压力测试解析
2023-06-09 01:55:45
![](https://img.aspxhome.com/file/2023/6/55506_0s.png)
Python中random函数的用法整理大全
2023-05-08 15:15:52
![](https://img.aspxhome.com/file/2023/6/92376_0s.png)
python中添加模块导入路径的方法
2021-12-17 14:35:30
Python离线安装openpyxl模块的步骤
2021-08-10 16:04:04
![](https://img.aspxhome.com/file/2023/6/89286_0s.png)
教你用一行Python代码实现并行任务(附代码)
2021-06-23 03:21:24
关于NumPy中asarray的用法及说明
2023-01-07 17:55:12
SQL语句分组获取记录的第一条数据的方法
2012-08-21 10:58:39
楼层数横排比竖排好
2008-04-26 07:28:00
![](https://img.aspxhome.com/file/UploadPic/20084/26/200842673425574s.jpg)
python pycharm的安装及其使用
2023-11-04 20:27:06
![](https://img.aspxhome.com/file/2023/8/80498_0s.jpg)
给Notepad++换主题
2009-05-04 14:43:00
![](https://img.aspxhome.com/file/UploadPic/20095/4/rhtml-39s.gif)
Python运算符重载用法实例分析
2023-03-18 07:28:11
Python如何使用函数做字典的值
2021-10-24 02:28:05
Python爬虫之网络请求
2023-10-29 21:28:08
![](https://img.aspxhome.com/file/2023/2/76072_0s.png)