Python字符串格式问题

Sha*_*mar 2 python string

import random

def main():
    the_number = random.randint(1,100)
    guess = 0
    no_of_tries = 0
    while guess != the_number:
        no_of_tries += 1
        guess = int(input("Enter your guess: "))
        if guess < the_number:
            print "--------------------------------------"
            print "Guess higher!", "You guessed:", guess
            if guess == the_number - 1:
                print "You're so close!"
        if guess > the_number:
            print "--------------------------------------"
            print "Guess lower!", "You guessed:", guess
            if guess == the_number + 1:
                print "You're so close!"
        if guess == the_number:
            print "--------------------------------------"
            print "You guessed correctly! The number was:", the_number
            print "And it only took you", no_of_tries, "tries!"

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

现在,在我的随机数猜测游戏中,如果一个人猜到一个数字更低或更高,他们会收到以下消息:

Guess lower! You guessed: 33
You're so close!
Run Code Online (Sandbox Code Playgroud)

但是我想把它写成一句话.

例如:

Guess lower! You guessed: 33. You're so close!
Run Code Online (Sandbox Code Playgroud)

我将如何在我的代码中实现这一点?谢谢!

Lev*_*von 6

如果你想避免它进入下一行,只需','在你的print陈述后面加一个逗号().例如:

print "Guess lower!", "You guessed:", guess,
                                           ^
                                           |
Run Code Online (Sandbox Code Playgroud)

下一个print语句将在此行的末尾添加其输出,即,它不会像您当前那样向下移动到下一行的开头.

更新以下评论:

为避免逗号引起的空间,可以使用打印功能.也就是说,

from __future__ import print_function  # this needs to go on the first line

guess = 33

print("Guess lower!", "You guessed:", guess, ".", sep="", end="")
print(" You're so close!")
Run Code Online (Sandbox Code Playgroud)

这将打印

Guess lower!You guessed:33. You're so close!

PEP还讨论了打印功能