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实现应用程序在右键菜单中添加打开方式功能

python实现应用程序在右键菜单中添加打开方式功能

最近项目组开发的一个小工具想要在右键菜单中添加打开方式,以有道云笔记为例进行了需求拆解和代码编写 1.需求拆解: 如何实现手动添加右键菜单的打开方式: Step1:打开注册表编辑器,Wi...

Python中pygame的mouse鼠标事件用法实例

Python中pygame的mouse鼠标事件用法实例

本文实例讲述了Python中pygame的mouse鼠标事件用法。分享给大家供大家参考,具体如下: pygame.mouse提供了一些方法获取鼠标设备当前的状态 ''' pygame...

Python检测一个对象是否为字符串类的方法

目的   测试一个对象是否是字符串 方法 Python的字符串的基类是basestring,包括了str和unicode类型。一般可以采用以下方法: 复制代码 代码如下: def isA...

python+webdriver自动化环境搭建步骤详解

python+webdriver自动化环境搭建步骤详解

python是一个很好脚本语言工具,现在也比较流行的一个脚本语言工具,对目前web自动化可以用的比较是webdriver框架进行自动化测试,脚本写起来较简单,运行的占用的内容较小。那么对...

python装饰器相当于函数的调用方式

1. 普通装饰器 import logging 1. foo = use_loggine(foo) def use_loggine(func): def wrapper(...