How To Reverse A String in Python

Unlike other languages such as Ruby, there is no built-in method to reverse a string in Python. Here are two possible ways to accomplish that: 

1) The 'Long' Way

This approach uses a for-loop with the join method to reverse a string:

def rev(s):
    return ''.join([s[i] for i in range(len(s)-1,-1,-1)])

>>> print rev("abcde")
edcba

2) The Simpler Way

This approach uses Python's 'slice notation' to accomplish the same result:

def rev(s):
    return s[::-1]
   
>>> print rev("abcde")
edcba

I think I read somewhere that #1 (for-loop) is faster, but I do love the simplicity of slicing. It looks a little strange at first, if you're not used to Python. But it really is pretty easy to use once you get the hang of it.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>