Sri Sri - 3 years ago 80
Python Question

Python: String reverse stops halfway

I'm writing a function to reverse a string, but it doesn't complete it till the end. Am I missing something here?

def reverse_string(str):
straight=list(str)
reverse=[]
for i in straight:
reverse.append(straight.pop())
return ''.join(reverse)

print ( reverse_string('Why is it not reversing completely?') )

Answer Source

The problem is that you pop elements from the original and thereby change the length of the list, so the loop will stop at half the elements.

Typically this is solved by creating a temporary copy:

def reverse_string(a_str):
    straight=list(a_str)
    reverse=[]
    for i in straight[:]:  # iterate over a shallow copy of "straight"
        reverse.append(straight.pop())
    return ''.join(reverse)

print(reverse_string('Why is it not reversing completely?'))
# ?yletelpmoc gnisrever ton ti si yhW

However in case of reversing you can use already existing (easier) alternatives:

Slicing:

>>> a_str = 'Why is it not reversing completely?'
>>> a_str[::-1]
'?yletelpmoc gnisrever ton ti si yhW'

or the reversed iterator:

>>> ''.join(reversed(a_str))
'?yletelpmoc gnisrever ton ti si yhW'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download