Ways to Reverse a string using Python

A Classic Interview Question is to ask to reverse a string.

Many ways exist and it can be fun to use an original method.

Play with it and come up with an original way to do this

List Comprehension

my_str="hello world"

str_rev=[my_str[len(my_str)-i-1] for i in range(len(my_str))]

print str_rev

iterative

my_str="hello world" my_len=len(my_str)

my_list=list(my_str)

for i in range(my_len/2): print i , my_len-i print " ",my_list[i],my_list[my_len-i-1] (my_list[i],my_list[my_len-i-1])=(my_list[my_len-i-1],my_list[i])

my_str="".join(my_list)

print my_list

recursive

def rev_string(my_str): if len(my_str)>1: return rev_string(my_str[int(len(my_str)/2):])+rev_string(my_str[:int(len(my_str)/2)]) else: return my_str

print rev_string("hello world")

Array Slices

a=[0,1,2,3]

print a[::-1]