Python Cookbook 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*
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值