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

yipeiwu_com5年前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 tkinter实现图片标注功能(完整代码)

.tkinter tkinter是Python下面向tk的图形界面接口库,可以方便地进行图形界面设计和交互操作编程。tkinter的优点是简单易用、与Python的结合度好。tkinte...

python3中pip3安装出错,找不到SSL的解决方式

最近在Ubuntu16.04上安装Python3.6之后,使用pip命令出现了问题,提示说找不到ssl模块,出现错误如下: pip is configured with locati...

使用 Supervisor 监控 Python3 进程方式

使用 Supervisor 监控 Python3 进程方式

首先说明,Supervisor 只能安装在 Python 2.x 环境中! 但是基本上所有的 Linux 都同时预装了 Python 2.x 和 Python 3.x 版本,并且调用 p...

Python操作MySQL数据库9个实用实例

Python操作MySQL数据库9个实用实例

在Windows平台上安装mysql模块用于Python开发 用python连接mysql的时候,需要用的安装版本,源码版本容易有错误提示。下边是打包了32与64版本。 MySQL-py...

python实现基本进制转换的方法

本文实例讲述了python基本进制转换的方法。分享给大家供大家参考。具体如下: # Parsing string with base into a number is easy nu...