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 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:
revchars = list(astring) # string -> list of chars revchars.reverse( ) # reverse the list in place revchars = ''.join(revchars) # list of strings -> string
To flip words, we just work with a list of words instead of a list of characters:
revwords = astring.split( ) # string -> list of words revwords.reverse( ) # reverse the list in place 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:
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 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access