简体   繁体   中英

How do i reverse a string in python using lists and pop()

I am writing a function to take a string and reverse it. I can't work out why my code is returning a reversed string but with only half of the letters of the string passed to it.

   def reverse(text):
        temp = []
        reverse_text = ""
        for i in text:
            temp.append(i)
        for i in temp:
            reverse_text += temp.pop()
        print reverse_text

I'm not going to post a complete answer, but:

  1. Don't modify a list you're iterating over with a for loop. Bad things will happen (you already realized that)

  2. You therefore can use a while loop to accomplish the task.

  3. You can also use a for loop, but then you'll end up with for i in range(len(temp)): (see other answers), and the range(len(..)) construct is rather "unpythonic".

def reverse(text)
    return text[::-1]

我只会用reversedString = string[::-1] ,这是我认为最简单的方法。

for i in range(len(text)):
    reverse_text += temp.pop()

don't change the string.

Every time you are doing pop operation you are changing the temp over which you are iterating as well.

A simple way would be to just do pop n times where n is the length of temp

def reverse(text):
    temp = []
    reverse_text = ""
    for i in text:
        temp.append(i)
    print temp
    for i in range(len(temp)):
#         print i, temp[i]
        reverse_text += temp.pop()
    print reverse_text

If you can't do:

text[::-1]

Try doing a for loop:

text = 'Hello'
product=''
for x in range(len(text)-1, -1, -1):
    product+=text[x]
return product

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM