2012-07-16 120 views
2
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() 

現在,在我的隨機數字猜謎遊戲,如果一個人猜測較低或較高的一個號碼,他們會收到以下消息:Python字符串格式化問題

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

但我想讓它一個句子。

例如:

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

我怎麼會在我的代碼實現這一點?謝謝!

回答

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也會談

+0

謝謝,但如果想要把一個時期的消息之前,像「你太親密了!」,33和。之間沒有差距嗎?有沒有辦法連接它們? – 2012-07-16 23:55:43

+0

@ShankarKumar查看最新的答案。 – Levon 2012-07-17 00:02:05

+0

謝謝你的回答! – 2012-07-17 00:08:10