Python字符串格式问题

时间:2012-07-16 23:48:00

标签: 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()

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

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

但我想说一句话。

例如:

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

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

1 个答案:

答案 0 :(得分:6)

如果您想避免它前进到下一行,只需在','语句后面添加一个逗号(print)。例如:

print "Guess lower!", "You guessed:", guess,
                                           ^
                                           |

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

更新重新评论

为了避免逗号引起的空格,您可以使用print function。即,

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!")

这将打印

  

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

这个PEP也谈到了打印功能

相关问题