如何在 Python 的同一行上打印变量和字符串? [英] How can I print variable and string on same line in Python?
问题描述
我正在使用 python 计算如果每 7 秒就有一个孩子出生,那么 5 年内会出生多少个孩子.问题出在我的最后一行.当我在变量的任一侧打印文本时,如何让变量起作用?
这是我的代码:
currentPop = 312032486一年 = 365小时 = 24分钟 = 60秒 = 60# 一天内的秒数secondsInDay = 小时 * 分钟 * 秒# 一年中的秒数secondsInYear = secondsInDay * oneYear五年 = secondsInYear * 5#5 年内的秒数印刷五年# 以秒为单位的五年,除以 7 秒出生数 = 五年//7print "如果每 7 秒就有一次出生,将会有:"births "births"
使用 ,
在打印时分隔字符串和变量:
print("如果每 7 秒有一次出生,将会有:",births, "births")
,
在打印函数中用一个空格分隔项目:
或者更好地使用字符串格式:
print("如果每 7 秒有一次出生,就会有:{}births".format(births))
字符串格式要强大得多,还允许您做一些其他的事情,例如填充、填充、对齐、宽度、设置精度等.
<预><代码>>>>打印({:d} {:03d} {:>20f}".format(1, 2, 1.1))1 002 1.100000^^^0 填充为 2演示:
<预><代码>>>>出生数 = 4>>>print("如果每 7 秒有一次出生,将会有:",births, "births")如果每 7 秒就有一次出生,将会有: 4 次出生# 格式化>>>打印(如果每 7 秒有一次出生,就会有:{} 出生".格式(出生))如果每 7 秒就有一次出生,将会有: 4 次出生I am using python to work out how many children would be born in 5 years if a child was born every 7 seconds. The problem is on my last line. How do I get a variable to work when I'm printing text either side of it?
Here is my code:
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"
Use ,
to separate strings and variables while printing:
print("If there was a birth every 7 seconds, there would be: ", births, "births")
,
in print function separates the items by a single space:
>>> print("foo", "bar", "spam")
foo bar spam
or better use string formatting:
print("If there was a birth every 7 seconds, there would be: {} births".format(births))
String formatting is much more powerful and allows you to do some other things as well, like padding, fill, alignment, width, set precision, etc.
>>> print("{:d} {:03d} {:>20f}".format(1, 2, 1.1))
1 002 1.100000
^^^
0's padded to 2
Demo:
>>> 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 的同一行上打印变量和字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!