DEV Community

Cover image for Reversing a string
Kwith Code
Kwith Code

Posted on • Edited on

Reversing a string

How to create a reverse string function in python

In order to reverse a string in python and make our code reusable, first we need to define a function. In that function you'll have a parameter taking in a string,

def reverseStr(data:str)

two variables, one containing a split-word list and the other where we'll add a reversed string of letters
of the given string,

splitWord = list(data)
reversedWord = ''
Enter fullscreen mode Exit fullscreen mode

a loop, in this loop we'll iterate by the value of the length of the split-word list and in each iteration
we'll add the index value of the length of the split-word list(len(splitWord)) minus the iteration number(i)
to the reversedWord making one reversed word.

for i in range(len(splitWord)):
    reversedWord += splitWord[(len(splitWord)-1)-i]
Enter fullscreen mode Exit fullscreen mode

and finaly our work is done. Enjoy your day.

def reverseStr(data:str):
    splitWord = list(data)
    reversedWord = ''

    for i in range(len(splitWord)):
        reversedWord += splitWord[(len(splitWord)-1)-i]


    return reversedWord
Enter fullscreen mode Exit fullscreen mode

let's test it:

def Run():
    word = 'Monopoly'
    print(reverseStr(word))

Run()
Enter fullscreen mode Exit fullscreen mode

GitHub logo Heli9x / Codepens

A bunch of fun code to get u

Codepens

A bunch of fun code to get you on track or in line.






Top comments (0)