Python Forum
printing a string in reverse - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: printing a string in reverse (/thread-35590.html)



printing a string in reverse - Skaperen - Nov-20-2021

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..


RE: printing a string in reverse - bowlofred - Nov-20-2021

If it's a string, then you can create a reversed string by slicing with a -1 step..

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



RE: printing a string in reverse - ghoul - Nov-20-2021

(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