我的字符串输出为什么缺少一个字母?

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

Why does my string output have a missing letter?

问题

我不理解输出

输入
name = 'World'
line = '-'
for char in name:
    print(line)
    line = line + char

输出
-
-W
-Wo
-Wor
-Worl

为什么没有 -World

非常困惑。第一天学习Python。没有任何其他编程语言的先前知识。

英文:

I don't understand the output

INPUT
name = 'World'
line = '-'
for char in name:
    print(line)
    line = line + char

OUTPUT
-
-W
-Wo
-Wor
-Worl

why is there no -World

very confused. first day learning python. no prior knowledge of any language

答案1

得分: 0

这是因为在添加字符之前你先打印了这行。

如果你想要打印整个单词,你需要在打印之前设置好 line 变量。

name = 'World'
line = '-'
for char in name:
    line = line + char
    print(line)

我假设这是为了练习,但如果你只想在单词前面打印连字符,你不需要循环,可以直接写成 print(line + name)

英文:

It happens because you are printing the line before adding the character.

If you want to print the whole word you need to set the line variable before printing it.

name = 'World'
line = '-'
for char in name:
    line = line + char
    print(line)

I assume this is for an exercise, but if you just want to print the word with the dash in front of it, you don't need the loop, and can instead write print(line + name).

答案2

得分: 0

问题在于在打印line之后,您只是将linename连接起来。因此,在循环的最后一次迭代中,它会打印“-Worl”,然后才将“d”添加到line。如果在循环外再次打印line,输出将是“-World”。

您可以通过更改循环内部的行顺序来解决此问题:

for char in name:
    line = line + char
    print(line)    
英文:

The problem is that you're only concatenating line and name after printing line. So, on the last iteration of the loop, it prints "-Worl" and then adds the 'd' to line. If you print line again outside the loop, the output will be "-World".

You can fix this by changing the order of the lines inside the loop to:

for char in name:
    line = line + char
    print(line)    

huangapple
  • 本文由 发表于 2023年6月11日 19:57:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450363.html
匿名

发表评论

匿名网友

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

确定