[英]Python string formatting issue
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!
如何在我的代碼中實現呢? 謝謝!
如果要避免前進到下一行','
只需在print
語句后加上一個逗號( ','
)。 例如:
print "Guess lower!", "You guessed:", guess,
^
|
下一條 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!")
這將打印
Guess lower!You guessed:33. You're so close!
該PEP還討論了打印功能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.