gpt4 book ai didi

python - 如何在 Python 的同一行上打印变量和字符串?

转载 作者:IT老高 更新时间:2023-10-28 12:32:02 26 4
gpt4 key购买 nike

我正在使用 python 计算如果每 7 秒有一个 child 出生,5 年内将出生多少个 child 。问题出在我的最后一行。当我在它的任一侧打印文本时,如何让变量工作?

这是我的代码:

currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60

# seconds in a single day
secondsInDay = hours * minutes * seconds

# seconds in a year
secondsInYear = secondsInDay * oneYear

fiveYears = secondsInYear * 5

#Seconds in 5 years
print fiveYears

# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7

print "If there was a birth every 7 seconds, there would be: " births "births"

最佳答案

打印时使用,分隔字符串和变量:

print("If there was a birth every 7 seconds, there would be: ", births, "births")

, 在 print 函数中用一个空格分隔项目:

>>> print("foo", "bar", "spam")
foo bar spam

或更好地使用 string formatting :

print("If there was a birth every 7 seconds, there would be: {} births".format(births))

字符串格式化功能更强大,还允许您执行一些其他操作,例如填充、填充、对齐、宽度、设置精度等。

>>> print("{:d} {:03d} {:>20f}".format(1, 2, 1.1))
1 002 1.100000
^^^
0's padded to 2

演示:

>>> births = 4
>>> print("If there was a birth every 7 seconds, there would be: ", births, "births")
If there was a birth every 7 seconds, there would be: 4 births

# formatting
>>> print("If there was a birth every 7 seconds, there would be: {} births".format(births))
If there was a birth every 7 seconds, there would be: 4 births

关于python - 如何在 Python 的同一行上打印变量和字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17153779/

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