Python didn’t have any in-built String reverse function to reverse the given string. But you can use a slice that steps backward, -1, or other methods to do reverse string in Python.
txt = "Hello World"[::-1] print(txt)
Example String reverse function in Python
A simple example code created its own sting reverse function in Python.
def reverse(s): strg = "" for i in s: strg = i + strg return strg txt = "Hello World" print(reverse(txt))
Using extended slice syntax
The slice statement [::-1] means start at the end of the string and end at position 0, move with the step -1, negative one, which means one step backward.
def reverse(string): string = string[::-1] return string txt = "Hello World" print(reverse(txt))
Output: dlroW olleH
def reverse(s): if len(s) == 0: return s else: return reverse(s[1:]) + s txt = "Python" print(reverse(txt))
How to Reverse a String in Python?
Answer: The fastest and easiest way is to use a slice that steps backward,
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.
>>> 'hello world'[::-1] 'dlrow olleh'
Do comment if you have any doubts or suggestions on this Python function.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.