需要解释。

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

Need an explanation

问题

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

英文:
  1. startmsg = "hello"
  2. endmsg = ""
  3. for i in range(0,len(startmsg)):
  4. endmsg=startmsg[i] + endmsg
  5. print(endmsg)

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

答案1

得分: 3

以下是代码部分的翻译:

  1. 随着代码的迭代它将每个字母添加到之前迭代过的内容的前面最终结果是一个翻转后的字符串
  2. 在我们进行迭代时
  3. endmsg = "h"
  4. endmsg = "eh"
  5. endmsg = "leh"
  6. endmsg = "lleh"
  7. endmsg = "olleh"

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

  1. startmsg = "hello"
  2. endmsg = ""
  3. for ch in startmsg:
  4. endmsg = ch + endmsg
  5. 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:

  1. endmsg = "h"
  2. endmsg = "eh"
  3. endmsg = "leh"
  4. endmsg = "lleh"
  5. 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.

  1. startmsg = "hello"
  2. endmsg = ""
  3. for ch in startmsg:
  4. endmsg = ch + endmsg
  5. 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:

确定