Skip to main content
 首页 » 编程设计

python之从字符串末尾开始循环

2025年05月04日35myhome

我是一名 Python 初学者,在我们的一个类练习中,我们得到了一个我不太理解的解决方案。

问题:

Program that will reverse a string with a loop.

解决方法如下:

string = "Hello World" 
s = "" 
for ch in string: 
    s = ch + s 
print(s) 

我很困惑为什么这个循环从字符串的末尾开始。据我了解,新字符串应该与从头开始循环的字符串相同。谁能解释一下为什么?

请您参考如下方法:

让我们逐步完成:

for ch in string: 
  s = ch + s 

在 ch 和 s 迭代中将是:

ch = "H" 
s = "H" 
 
ch = "e" 
s = "eH" 
 
 
ch = "l" 
s = "leH" 
 
. 
. 
. 

您正在反转字符串,因为您不断将当前字符添加到现有字符串。