I came across a post about reversing strings in Python and it led me to write this post. Python strings do not come with a built-in .reverse() method as do lists. This leads many people to come up with their own versions of a string reverse. Two of the most common solutions that I have seen are below.
def reverse(s): r = "" for c in s: r = c + r return r s = "String to reverse." print reverse(s)
s = "String to reverse." print "".join(s[c] for c in xrange(len(s) - 1, -1, -1))
Probably the easiest and close to the fastest way to reverse a string is to use Python’s extended slice syntax. This allows you to specify a start, stop and step value to use when creating a slice. The syntax is: [start:stop:step].
s = "String to reverse." print s[::-1]
If start is omitted it defaults to 0 and if stop is omitted it defaults to the length of the string. A step of -1 tells Python to start counting by 1 from the stop until it reaches the start.
When working with large strings, or when you just don’t want to reverse the whole string at once, you can use the reversed() built-in. reversed() returns an iterator and is arguably the most Pythonic way to reverse a string.
s = "String to reverse." print "".join(reversed(s))