Reversing a string in Python using a loop? [duplicate]

烈酒焚心 提交于 2019-12-01 08:00:31

问题


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] methods here so it's a bit tricky.

My code looks something like this:

def reverse(text):
    while len(text) > 0:
        print text[(len(text)) - 1],
        del(text[(len(text)) - 1]

I use the , to print out every single letter in text on the same line!

I get invalid syntax on del(text[(len(text)) - 1]

Any suggestions?


回答1:


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



回答2:


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'



回答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.




回答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]


来源:https://stackoverflow.com/questions/41322315/reversing-a-string-in-python-using-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!