需要解释。

huangapple go评论53阅读模式
英文:

Need an explanation

问题

结果是 "olleh" 而不是 "hello",是因为在代码中进行了字符串翻转操作。代码中的循环迭代从字符串 "startmsg" 的末尾开始,将字符逐个添加到空字符串 "endmsg" 中,从而实现了字符串的反转。

英文:
startmsg = "hello"
endmsg = ""
for i in range(0,len(startmsg)):
    endmsg=startmsg[i] + endmsg
print(endmsg)

Why is the result: "olleh", a not "hello"?

答案1

得分: 3

以下是代码部分的翻译:

随着代码的迭代它将每个字母添加到之前迭代过的内容的前面最终结果是一个翻转后的字符串

在我们进行迭代时

endmsg = "h"

endmsg = "eh"

endmsg = "leh"

endmsg = "lleh"

endmsg = "olleh"

使用这种方式迭代索引在Python中不是特别惯用的方式。相反,如果不需要索引,直接迭代字符会更符合Python的风格。

startmsg = "hello"
endmsg = ""

for ch in startmsg:
    endmsg = ch + endmsg

print(endmsg)
英文:

As this code iterates, it adds each letter to the front of what's been iterated over previously. The end result is a reversed string.

As we iterate:

endmsg = "h"

endmsg = "eh"

endmsg = "leh"

endmsg = "lleh"

endmsg = "olleh"

Iterating over indexes like this is not particularly idiomatic Python. Rather, if the index is not needed, it would be more Pythonic to iterate over the characters directly.

startmsg = "hello"
endmsg = ""

for ch in startmsg:
    endmsg = ch + endmsg

print(endmsg)

huangapple
  • 本文由 发表于 2023年4月4日 14:04:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75925963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定