2007-06-14

 

Python Cook 1.7 反转字符串中的字符或单词

需求:

反转字符串中的单词或字符.

讨论:

如果是别的语言,通常的做法是写一个循环,然后利用临时变量,构造反转后的字符串.对于字符的反转,在Python中有一个非常简便的方法,利用切片功能.

newstring = astring[::-1]

这样,就能获得astring的反转字符串了.
对于单词的反转,可以利用序列的reverse方法:

words = astring.split()
words.reverse()
newstring = ' '.join(wrods)

这里我们假设单词之间是用空白字符分隔的.空白字符包括空格,回车,TAB等.
用一个语句表示的方法:

newstring = ' '.join(astring.split()[::-1])

这里我们用到了上面说的第一种方法.
看了上面两个方法,需要注意的时,string没有reverse方法.可能因为有了[::-1]已经满足了需求了吧.

如果单词间的分隔符不是空白字符,可以使用正则式来实现需求,如:

import re
newstring = re.split(r'(\s+)', astring)         # 用'()'分隔
newstring.reverse( )
newstring = ''.join(newstring)  

或者更简单的写法:

newstring = ''.join(re.split(r'(\s+)', astring)[::-1])

当然,如果这样写,就不符合Python的简单清晰的原则了.

相关说明:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings
    
    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator.

join(...)
    S.join(sequence) -> string
    
    Return a string which is the concatenation of the strings in the
    sequence.  The separator between elements is S.

reverse(...)
    L.reverse() -- reverse *IN PLACE*

关于正则式的说明请看后续的章节.

标签:


Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?