我想在for循环中打印可迭代对象后添加新行

0 投票
3 回答
59 浏览
提问于 2025-04-14 18:02

我在玩猜字游戏(hangman)。我把要猜的单词放进了一个列表里。我用一个循环来打印这个单词,每个字母之间有空格,而且我设置了结尾为"",这样它们就会在一行上打印出来。所有字母打印完后,我想把光标移动到新的一行。有没有什么优雅的方法可以做到这一点?有没有什么是打印功能的一部分呢?

hidden_word = list(r.get_random_word().lower())
for letters in hidden_word:
    print(f"{letters} ", end="")

这样打印出来的单词在一行上,每个字母之间有空格。

a b a c a d a b r a

那么,打印完后,怎么才能最好地换到下一行呢?

直接用 print() 吗?

还是说打印功能里有什么开关或者其他的东西?

3 个回答

-1

要在打印带空格的单词后把光标移动到新的一行,你可以简单地使用不带任何参数的print()函数。

hidden_word = list(r.get_random_word().lower())
for letter in hidden_word:

    print(f"{letter} ", end="")

# Move to the new line
print()
0

你有几种选择。哪个是“最好”的,这个是见仁见智的;你可以选择你觉得最简单的。这里有几种常见的方法:

word = r.get_random_word().lower() # note that strings are iterable without being `list`s

# option 1 (your suggestion is fine, but it adds a trailing space)
for letter in word:
  print(letter, end=" ")
print()

# option 2 (print the last character differently)
for index, character in enumerate(word):
  if index == len(word) - 1:
    print(character)
  else:
    print(character, end=" ")

# option 3 (unpack each character into separate arguments, automatically separated by a single space)
print(*word)

# option 4 (explicitly join the characters with a space between each one)
print(" ".join(word))

选项3和选项4显然是最简单(也是最短)的,所以更受欢迎。有人可能会说一个比另一个更好,但在大多数情况下,它们之间的差别微乎其微。

2

你可以在循环后面加一个 print

for letter in hidden_word:
    print(f"{letter} ", end="")
    # Or more clearly/with less work:
    print(letter, end=" ")
print()

或者你可以不使用循环,直接用 *-解包print 默认的空格来完成这个任务:

print(*hidden_word)

或者使用 str.join 手动在字母之间加上空格,然后打印出最终的字符串:

print(' '.join(hidden_word))

这几种方法都可以。第二种方法是最简洁直接的,但可能性能最差,不过你在做输入输出,所以CPU的开销其实没那么重要。

撰写回答