Sri
Sri

Reputation: 27

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?') )

Upvotes: 1

Views: 219

Answers (4)

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

You can use loop from the last index of list to zero index and then append in another list and then join to get reverse tring.

def reverse_string(str):
    straight=list(str)
    print straight
    reverse=[]
    for i in range(len(straight)-1,-1,-1):
        reverse.append(straight[i])
    return ''.join(reverse)


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

Upvotes: 0

MSeifert
MSeifert

Reputation: 152725

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'

Upvotes: 5

Billy Ferguson
Billy Ferguson

Reputation: 1439

There is an easier way to reverse:

>>> 'my string'[::-1]
'gnirts ym'

Upvotes: 1

T4rk1n
T4rk1n

Reputation: 1470

In python you can use steps iterator to reverse a string

print('hello'[::-1])

Will reverse the string

Upvotes: 1

Related Questions