英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论