Python:字符串反向中途停止

斯里

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

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

问题是你的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'

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章