0

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
2

6 Answers 6

4

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".

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

I would just use reversedString = string[::-1], most easy way I think.

2
  • Oh wow, they want more code while it could be done so simple? :-(
    – Tenzin
    Nov 14, 2015 at 10:47
  • 2
    yeah.. but someone had to write the code behind [::-1] ;)
    – shfury
    Nov 14, 2015 at 10:49
0

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
0
for i in range(len(text)):
    reverse_text += temp.pop()

don't change the string.

0
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.