Py&禅

博客园 首页 新随笔 联系 订阅 管理
Problem:
You want to reverse the characters or words in a string.

Solution:
使用字符串的切片操作  [start: stop : step], 当 step为-1时,可实现字符反转操作
revchars = astring [::-1]

为了实现words的反转,需要建立一个列表来保存words,
astring = 'hello world'
revwords = astring.split()   #string -> list of words
revwords.reverse()        #reverse the list in place
revwords = ' '.join(revwords)         #list of strings -> string
print revwords
world hello
或压缩成一条语句:
revwords = ' '.join(astring.split()[::-1])

使用 re.split()也能实现同样的功能:
import re
revwords = re.split('(\s+)', astring)
revwords.reverse()
revwords = ''.join(revwords)
print revwords
此时中间的空白字符也被保留在list中

Discussion:
也可以用內建函数reversed() 来取代切片操作 [::-1]来实现反转的功能
1.flip words
revwords = ' '.join(reversed(astring.split( )))
revwords = ''.join(reversed(re.split(r'(\s+)', astring)))
2. flip chars
revchars = ''.join(reversed(astring))




posted on 2010-05-31 12:43  Py&禅  阅读(246)  评论(0)    收藏  举报