Skip to main content
 首页 » 编程设计

Python:字符串反转中途停止

2025年05月04日24tuyile006

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

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

请您参考如下方法:

问题是您从原始元素中弹出元素,从而改变了列表的长度,因此循环将在元素的一半处停止。

通常这是通过创建一个临时副本来解决的:

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' 

或反向迭代器:

>>> ''.join(reversed(a_str)) 
'?yletelpmoc gnisrever ton ti si yhW'