Python实现单词反转效果


本文摘自php中文网,作者巴扎黑,侵删。

这篇文章主要为大家详细介绍了Python字符串处理实现单词反转的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

Python字符串处理学习中,有一道简单但很经典的题目,按照单词对字符串进行反转,并对原始空格进行保留:
如:‘ I love China! ‘
转化为:‘ China! love I ‘

两种解决方案:

方案1:从前往后对字符串进行遍历,如果第一个就是空格,直接跳过,直到第一个不是空格的字符,如果是单独的字母,同样跳过,否则的话,将该单词进行反转,再往后遍历,最后使用reserve方法,让整个字符串从后往前打印。

方案2:直接使用re(正则化)包进行反转

代码如下:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

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 3.6?

新手Python用什么版本好?

Python前景怎么样

Python中什么是运算符

Python下如何实现文件的修改操作?(附示例)

记录一次简单的Python爬虫实例

怎样在Python求和

剪刀石头布用Python怎么写

Python记录程序运行时间的方法介绍

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...