文章来自《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:
To flip words, we just work with a list of words instead of a list of characters:
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:
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.
讨论 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:
or maybe this, which is messier and slower:
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:
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.