Python: 字符串反转中途停止
Python: String reverse stops halfway
我正在编写一个函数来反转字符串,但它直到最后才完成。我在这里遗漏了什么吗?
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?') )
在 python 中,您可以使用步骤迭代器来反转字符串
print('hello'[::-1])
将反转字符串
有一个更简单的逆转方法:
>>> 'my string'[::-1]
'gnirts ym'
问题是你 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'
您可以使用从列表的最后一个索引到零索引的循环,然后在另一个列表中使用 append
,然后使用 join
来获得反向字符串。
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?') )
我正在编写一个函数来反转字符串,但它直到最后才完成。我在这里遗漏了什么吗?
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?') )
在 python 中,您可以使用步骤迭代器来反转字符串
print('hello'[::-1])
将反转字符串
有一个更简单的逆转方法:
>>> 'my string'[::-1]
'gnirts ym'
问题是你 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'
您可以使用从列表的最后一个索引到零索引的循环,然后在另一个列表中使用 append
,然后使用 join
来获得反向字符串。
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?') )