本文摘自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))
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安装包里idle在哪
Python入门教程之列表操作
linux如何安装Python
一款对Python初学者友好的编辑器
安装Python后如何打开
Python实现爬虫设置代理ip和伪装成浏览器的方法分享
Python闰年判定代码是什么
Python后端开发需要学什么?
Python中set()函数详解
用Python画星空源代码是什么?
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python实现单词反转效果