Recipe1.7.Reversing a String by Words or Characters


Recipe 1.7. Reversing a String by Words or Characters

Credit: Alex Martelli

Problem

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

Solution

Strings are immutable, so, to reverse one, we need to make a copy. The simplest approach for reversing is to take an extended slice with a "step" of -1, so that the slicing proceeds backwards:

revchars = astring[::-1]

To flip words, we need to make a list of words, reverse it, and join it back into a string with a space as the joiner:

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

or, if you prefer terse and compact "one-liners":

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

If you need to reverse by words while preserving untouched the intermediate whitespace, you can split by a regular expression:

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

Note that the joiner must be the empty string 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). Again, you could make a one-liner, if you wished:

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

but this is getting too dense and unreadable to be good Python code!

Discussion

In Python 2.4, you may make the by-word one-liners more readable by using the new built-in function reversed instead of the less readable extended-slicing indicator [::-1]:

revwords = ' '.join(reversed(astring.split( ))) revwords = ''.join(reversed(re.split(r'(\s+)', astring)))

For the by-character case, though, astring[::-1] remains best, even in 2.4, because to use reversed, you'd have to introduce a call to ''.join as well:

revchars = ''.join(reversed(astring))

The new reversed built-in returns an iterator, suitable for looping on or for passing to some "accumulator" callable such as ''.joinit does not return a ready-made string!

See Also

Library Reference and Python in a Nutshell docs on sequence types and slicing, and (2.4 only) the reversed built-in; Perl Cookbook recipe 1.6.



Python Cookbook
Python Cookbook
ISBN: 0596007973
EAN: 2147483647
Year: 2004
Pages: 420

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net