Reputation: 27
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
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
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
Reputation: 1439
There is an easier way to reverse:
>>> 'my string'[::-1]
'gnirts ym'
Upvotes: 1
Reputation: 1470
In python you can use steps iterator to reverse a string
print('hello'[::-1])
Will reverse the string
Upvotes: 1