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 = ''
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]
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
let's test it:
def Run():
word = 'Monopoly'
print(reverseStr(word))
Run()
Codepens
A bunch of fun code to get you on track or in line.
Top comments (0)