Python:字符串反向中途停止

Sri*_*Sri 1 python string reverse python-3.x

我正在编写一个函数来反转一个字符串,但直到最后才完成它.我在这里错过了什么吗?

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?') )
Run Code Online (Sandbox Code Playgroud)

MSe*_*ert 5

问题是你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
Run Code Online (Sandbox Code Playgroud)

但是,如果是倒车,您可以使用现有(更简单)的替代方案:

切片:

>>> a_str = 'Why is it not reversing completely?'
>>> a_str[::-1]
'?yletelpmoc gnisrever ton ti si yhW'
Run Code Online (Sandbox Code Playgroud)

或者reversed迭代器:

>>> ''.join(reversed(a_str))
'?yletelpmoc gnisrever ton ti si yhW'
Run Code Online (Sandbox Code Playgroud)