Friday, March 15, 2013

Reverse a string in Python

Reverse a string in Python

How about:
>>> 'hello world'[::-1]
'dlrow olleh'

This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.

s[::-1] is fastest; a slower approach (maybe more readable, but that's debatable) approach is  

c = list(string1)
print ''.join(c)


Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

No comments:

Post a Comment