I want to reverse a string without slicing it but only using reverse function. So how can I use reverse function to reverse a string?
With the improved support for Unicode in Python3, more and more folks will be working with languages (Arabic, Hebrew, etc.) that read right-to-left rather than left-to-right. So more and more folks will have a need to reverse a string.
Unfortunately, Python doesn’t have a built-in function, nor do string objects have a built-in method, to do what they will want. The obvious techniques don’t work. This:
try: print(1) s = "a b c" s = reverse(s) print(s) except Exception as e: print(e) try: print(2) s = "a b c" s = reversed(s) print(s) except Exception as e: print(e) try: print(3) s = "a b c" s.reverse() print(s) except Exception as e: print(e) try: print(4) s = "a b c" s.reversed() print(s) except Exception as e: print(e)
produces this output
1 name 'reverse' is not defined 2 <reversed object at 0x00BAB5F0> 3 'str' object has no attribute 'reverse' 4 'str' object has no attribute 'reversed'
Fortunately, the solution is not too difficult. A little one-line function will do the trick.
I call the function “rev” rather than “reverse” on the chance that Python will eventually acquire its own builtin function named “reverse”.
def rev(s): return s[::-1]