问题:
反转字符串中的单词或字符.
解决方法:
如果是别的语言,通常的做法是写一个循环,然后利用临时变量,构造反转后的字符串.对于字符的反转,在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*
反转字符串中的单词或字符.
解决方法:
如果是别的语言,通常的做法是写一个循环,然后利用临时变量,构造反转后的字符串.对于字符的反转,在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*
本文介绍了在Python中如何简便地反转字符串中的字符及单词。对于字符的反转,利用Python的切片功能可以轻松实现。而对于单词的反转,则可以通过split和reverse方法结合使用。此外,文章还讨论了当单词间分隔符不是空白字符时,如何使用正则表达式来完成需求。
168

被折叠的 条评论
为什么被折叠?



