在 Python 中将字符串与 int 连接起来:Jack and the Beanstalk



我是python的新手,在连接我的打印字符串以显示我想要的方式显示数据时遇到问题。我对python知之甚少,并且一直在尝试使用我从java中学到的大部分内容来做到这一点。正确格式的解释会有所帮助,提前谢谢。

法典:

print("The Magic Beanstalkn")
height = 100
hours = input("Enter a number of hours: ")
string1 = "After 1 hour, the beanstalk was %d cm tall.", height
print(string1)
for i in hours:
height = height*1.5 + 30
print("After %d hours, the beanstalk was %d cm tall. ", hours, height)
print("And it's still growing!!!")

输出:

The Magic Beanstalk

Enter a number of hours: 3
('After 1 hour, the beanstalk was %d cm tall.', 100)
After %d hours, the beanstalk was %d cm tall.  3 180.0
And it's still growing!!!

如您所见,我尝试直接从对对象的调用和打印语句中打印出来,这两者都没有给我所需的结果。

你可以做

string1 = "After 1 hour, the beanstalk was {} cm tall.".format(height)
print("After {} hours, the beanstalk was {} cm tall. ".format(hours, height))

或 string1 = f"1小时后,豆茎高{高}厘米。 打印(f"在{小时}小时后,豆茎高{高}厘米。") f 字符串的第二个选项来自 python 3.6 或更高版本。

使用格式说明符尝试以下方法:

string1 = "After 1 hour, the beanstalk was %d cm tall." % height

或使用格式方法:

string1 = "After 1 hour, the beanstalk was {0} cm tall.".format(height)

相关内容

最新更新