Reverse a string in Python
How about:
Method-1
Method-1
>>> '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.Method-2
s[::-1]
is fastest; a slower approach (maybe more readable, but that's debatable) approach is
''.join(reversed(s))
. Method-3
c = list(string1)
c.reverse()
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