且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-04 11:39:58

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

print("如果每 7 秒有一次出生,将会有:",births, "births")

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

>>>打印(foo",bar",垃圾邮件")foo 酒吧垃圾邮件

或者更好地使用字符串格式:

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