Reversing a string in Python

Posted: 25th April 2013 by Tim in Python
Tags: , , , , , , , ,

If you need to reverse a string in python, the easiest way is to do use the my_string[::-1] syntax. For example, to print a reversed string, you could write:

my_string = "ABCDE"
print my_string[::-1]

So what is this doing? The square bracket syntax is used for returning a substring. This works like so: [<start>:<end>:<step>]. If <start> and/or <end> are not specified, as in the example above, the start and end of the string is used instead. For example, my_string[:3] would return ABC.

The last parameter, <step> is optional. If provided, the substring will use every step‘th character when building the string. For example, my_string[0:5:2] would return ACE; the 1st, 3rd and 5th character. If a negative number is provided for <step>, the string will be constructed from the end instead of the beginning.

So for our example program, my_string[::-1] constructs a substring of ABCDE using all characters (beginning to end), traversed backwards over every character. In other words, it reverses the string.