Python字符串处理:按单词反转
来源:互联网 发布:linux显示行数 编辑:程序博客网 时间:2024/06/06 15:53
python字符串处理学习中,有一道简单但很经典的题目,按照单词对字符串进行反转,并对原始空格进行保留:
如:‘ I love China! ‘
转化为:‘ China! love I ‘
两种解决方案:
方案1:从前往后对字符串进行遍历,如果第一个就是空格,直接跳过,直到第一个不是空格的字符,如果是单独的字母,同样跳过,否则的话,将该单词进行反转,再往后遍历,最后使用reserve方法,让整个字符串从后往前打印。
方案2:直接使用re(正则化)包进行反转
代码如下:
import redef reserve(str_list, start, end): while start <= end: str_list[start], str_list[end] = str_list[end], str_list[start] end -= 1 start += 1str = ' I love china! 'str_list = list(str)print(str_list)i = 0print(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 += 1print(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)
阅读全文
0 0
- Python字符串处理:按单词反转
- 字符串处理之反转单词
- 按单词反转字符串
- 按单词反转字符串
- 按单词反转字符串
- 按单词反转字符串
- 按单词反转字符串
- 按单词反转字符串
- 字符串反转,单词反转
- LeetCode按单词反转字符串
- Easy:字符串按单词反转
- 笔试题-反转字符串和按单词反转字符串
- 面试问题之 按单词反转字符串
- 面试问题之 按单词反转字符串
- 简单面试题::字符串按单词反转
- 字符串单词顺序反转
- 反转字符串中的单词
- 字符串中单词反转
- 关于float有效位数为7位的研究
- SylixOS 定长内存管理
- uva 10082
- iOS-音频
- 页框page
- Python字符串处理:按单词反转
- 8. String to Integer (atoi)
- iOS-视频
- Java知识小结—(1)
- Hadoop学习笔记十一 使用Oozie自动化数据处理(未完)
- 重写Object常用的方法
- 解决mysql数据库:Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)问题
- git 学习资料
- iOS-地图的简单应用