Reversing a string

suggest change

A string can be reversed using the built-in reversed() function, which takes a string and returns an iterator in reverse order.

>>> reversed('hello')  # <reversed object at 0x...>; the address varies
>>> [char for char in reversed('hello')]
['o', 'l', 'l', 'e', 'h']

reversed() can be wrapped in a call to ''.join() to make a string from the iterator.

>>> ''.join(reversed('hello'))
'olleh'

While using reversed() might be more readable to uninitiated Python users, using extended slicing with a step of -1 is faster and more concise. Here , try to implement it as function:

>>> def reversed_string(main_string):
...     return main_string[::-1]
...
>>> reversed_string('hello')
'olleh'

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents