String reverse function in Python | Basic code

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]

Example String reverse function in Python

Simple example code created its own sting reverse function in Python.

Using loop

def reverse(s):
    strg = ""
    for i in s:
        strg = i + strg
    return strg

txt = "Hello World"



String reverse function in Python

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"


Output: dlroW olleH

Using recursion

def reverse(s):
    if len(s) == 0:
        return s
        return reverse(s[1:]) + s[0]

txt = "Python"


Output: nohtyP

How to Reverse a String in Python?

Answer: The fastest and easiest way is to use a slice that steps backward, -1.

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 and suggestions on this Python function.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.