Skip to content

String reverse function in Python | Basic code

  • by

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.

Using loop


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


txt = "Hello World"

print(reverse(txt))

Output:

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"

print(reverse(txt))

Output: dlroW olleH

Using recursion

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


txt = "Python"

print(reverse(txt))

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading