gpt4 book ai didi

Python字符串格式问题

转载 作者:行者123 更新时间:2023-11-28 21:27:11 27 4
gpt4 key购买 nike

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 语句将在这一行的末尾 添加它的输出,也就是说,它不会像您当前那样向下移动到下一行的开头。

更新下面的评论:

要避免逗号引起的空格,您可以使用 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还讲到了打印功能

关于Python字符串格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514219/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com