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):
for i in straight:
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):
    for i in straight[:]:  # iterate over a shallow copy of "straight"
    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:


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