Python Forum

Full Version: printing a string in reverse
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a string in a variable x. i want to print that string in reverse order. like:
Output:
>>> x = 'foobar' >>> print(rev(x)) raboof >>>
... assuming rev() does the job for me. but if there is no rev()], what to code? i am not interested in answers without working code. i have tried reversed() and sorted(...,reverse=True) and have not yet found a nice compact solution.

if someone wants to implement rev(), try to make sure it will reverse the order of any sequence and return the very same type it was given..
If it's a string, then you can create a reversed string by slicing with a -1 step..

>>> x = "foobar"
>>> print(x[::-1])
raboof
(Nov-20-2021, 12:54 AM)bowlofred Wrote: [ -> ]If it's a string, then you can create a reversed string by slicing with a -1 step..

>>> x = "foobar"
>>> print(x[::-1])
raboof

That looks super handy. I would have taken the route to manually reverse the string myself