Python字符串处理实现单词反转

yipeiwu_com6年前Python基础

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设计】。

相关文章

分析并输出Python代码依赖的库的实现代码

用法: 分析一个脚本的依赖: analysis_dependency.py script1.py 递归分析依赖: analysis_dependency.py script1.py -r...

Django框架 Pagination分页实现代码实例

一、自定义分页 1、基础版自定义分页 data = [] for i in range(1, 302): tmp = {"id": i, "name": "alex-{}...

探索Python3.4中新引入的asyncio模块

使用 Simple Protocol asyncio.BaseProtocol 类是asyncio模块中协议接口(protocol interface)的一个常见的基类。asyncio....

Python 元类实例解析

Python 元类实例解析

龟叔发明了 Python,然后集成了一堆概念在这门语言里面,比如:迭代器,装饰器,函数,生成器,类,对象,协程等等。 这些概念对初学者似乎没一个好懂的,不过还有比这更难的概念,它是 Py...

详解django2中关于时间处理策略

详解django2中关于时间处理策略

一、django中数据模型关于时间字段的认识 1、 DateField :可以记录年月日,映射到数据库是 date 类型 2、 DateTimeField :可以记录年月日时分秒,映射到...