Skip to content Skip to sidebar Skip to footer

Reversing A String In Python Using A Loop?

I'm stuck at an exercise where I need to reverse a random string in a function using only a loop (for loop or while?). I can not use '.join(reversed(string)) or string[::-1] method

Solution 1:

Python string is not mutable, so you can not use the del statement to remove characters in place. However you can build up a new string while looping through the original one:

def reverse(text):
    rev_text = ""
    for char in text:
        rev_text = char + rev_text
    return rev_text

reverse("hello")
# 'olleh'

Solution 2:

The problem is that you can't use del on a string in python. However this code works without del and will hopefully do the trick:

def reverse(text):
    a = ""
    for i in range(1, len(text) + 1):
        a += text[len(text) - i]
    return a

print(reverse("Hello World!")) # prints: !dlroW olleH

Solution 3:

Python strings are immutable. You cannot use del on string.

text = 'abcde'
length = len(text)
text_rev = ""
while length>0:
   text_rev += text[length-1]
   length = length-1

print text_rev

Hope this helps.


Solution 4:

Here is my attempt using a decorator and a for loop. Put everything in one file.

Implementation details:

def reverse(func):
    def reverse_engine(items):
        partial_items = []
        for item in items:
            partial_items = [item] + partial_items
        return func(partial_items)
    return reverse_engine

Usage:

Example 1:

@reverse
def echo_alphabets(word):
    return ''.join(word)

echo_alphabets('hello')
# olleh

Example 2:

@reverse
def echo_words(words):
    return words

echo_words([':)', '3.6.0', 'Python', 'Hello'])
# ['Hello', 'Python', '3.6.0', ':)']

Example 3:

@reverse
def reverse_and_square(numbers):
    return list(
        map(lambda number: number ** 2, numbers)
    )

reverse_and_square(range(1, 6))
# [25, 16, 9, 4, 1]

Post a Comment for "Reversing A String In Python Using A Loop?"