Python 3:在同一行上打印

时间:2013-10-15 17:18:43

标签: python printing

我正在尝试为我的Hangman游戏概念在同一行上打印文本。它工作得更早,虽然从大多数错误中解决了游戏后,我似乎无法让它发挥作用。用于打印的代码是:

def printWord():
    guessedWords = []
    guessedWordsCorrect = []
    selectedWord = 'dog'
    printWordLength = 0
    printWordIndex = 0
    printWord = ''

    while printWordLength < len(selectedWord):
        if selectedWord[printWordIndex] == " ":
                print(" ",end='')
                printWordLength = printWordLength + 1
                printWordIndex = printWordIndex + 1
        else:
            if selectedWord[printWordIndex] in guessedWords:
                print(selectedWord[printWordIndex],"",end='')
                printWordLength = printWordLength + 1
                printWordIndex = printWordIndex + 1
            else:
                print("_ ",end='')
                printWordLength = printWordLength + 1
                printWordIndex = printWordIndex + 1
        print("")

我使用end=""尝试在同一行上打印,之前效果很好,但这次没有运气?

运行代码时,除了让它们在同一行上打印外,一切正常。

1 个答案:

答案 0 :(得分:1)

在打印没有换行符的内容后,每次循环迭代都会打印一个换行符:

while printWordLength < len(selectedWord):
    # ...
    print("")

将该打印语句移出循环:

while printWordLength < len(selectedWord):
    # ...

print("")