问题是你从原来的元素pop
,从而改变吨的长度他列出,所以循环将停止在一半的元素。
这通常是通过创建一个临时副本解决:在倒车,你可以使用已有的(容易)替代品的情况下
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
但是:
切片:
>>> a_str = 'Why is it not reversing completely?'
>>> a_str[::-1]
'?yletelpmoc gnisrever ton ti si yhW'
或reversed
迭代器:
>>> ''.join(reversed(a_str))
'?yletelpmoc gnisrever ton ti si yhW'
感谢@JohnColeman的澄清。我只是好奇为什么这个逻辑失败了。是的,这是一个坏主意;来自网站的代码挑战'str',我没有改变它 – Sri