文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- 0.706 [DateTime(2004-09-11T16:05:24Z)] TableOfContents

描述

...

问题 Problem

You want to reverse the characters or words in a string.

解决 Solution

Strings are immutable, so we need to make a copy. A list is the right intermediate data structure, since it has a reverse method that does just what we want and works in place:

   1 revchars = list(astring)       # string -> list of chars
   2 revchars.reverse(  )           # reverse the list in place
   3 revchars = ''.join(revchars)   # list of strings -> string

To flip words, we just work with a list of words instead of a list of characters:

   1 revwords = astring.split(  )       # string -> list of words
   2 revwords.reverse(  )               # reverse the list in place
   3 revwords = ' '.join(revwords)      # list of strings -> string

Note that we use a ' ' (space) joiner for the list of words, but a ' ' (empty string) joiner for the list of characters.

If you need to reverse by words while preserving untouched the intermediate whitespace, regular-expression splitting can be useful:

   1 import re
   2 revwords = re.split(r'(\s+)', astring)     # separators too since '(...)'
   3 revwords.reverse(  )                       # reverse the list in place
   4 revwords = ''.join(revwords)               # list of strings -> string

Note that the joiner becomes the empty string again in this case, because the whitespace separators are kept in the revwords list by using re.split with a regular expression that includes a parenthesized group.

   1 

讨论 Discussion

The snippets in this recipe are fast, readable, and Pythonic. However, some people have an inexplicable fetish for one-liners. If you are one of those people, you need an auxiliary function (you can stick it in your built-ins from sitecustomize.py) like this:

   1 def reverse(alist):
   2     temp = alist[:]
   3     temp.reverse(  )
   4     return temp

or maybe this, which is messier and slower:

   1 def reverse_alternative(alist):
   2     return [alist[i-1] for i in range(len(alist), 0, -1)]

This is, indeed, in-lineable, but not worth it in my opinion.

Anyway, armed with such an almost-built-in, you can now do brave new one-liners, such as:

   1 revchars = ''.join(reverse(list(astring)))
   2 revwords = ' '.join(reverse(astring.split(  )))

In the end, Python does not twist your arm to make you choose the obviously right approach: Python gives you the right tools, but it's up to you to use them.

参考 See Also

The Library Reference section on sequence types; Perl Cookbook Recipe 1.6.