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

新手上路,请多包涵

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

这是我的代码:

 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"

原文由 Bob Uni 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 561
2 个回答

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

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

, 在打印功能中用一个空格分隔项目:

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

或更好地使用 字符串格式

 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

原文由 Ashwini Chaudhary 发布,翻译遵循 CC BY-SA 4.0 许可协议

Python 是一种用途广泛的语言。您可以通过不同的方法打印变量。我在下面列出了五种方法。您可以根据自己的方便使用它们。

例子:

 a = 1
b = 'ball'

方法一:

 print('I have %d %s' % (a, b))

方法二:

 print('I have', a, b)

方法三:

 print('I have {} {}'.format(a, b))

方法四:

 print('I have ' + str(a) + ' ' + b)

方法五:

 print(f'I have {a} {b}')

输出将是:

 I have 1 ball

原文由 Gagan Agrawal 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题