为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

qq_笑_17 2021-03-29 17:05:45
我正在使用python算出如果一个孩子每7秒出生一次,那么5年内将有多少个孩子出生。问题出在我的最后一行。当我在文本的任何一侧打印文本时,如何使它工作?这是我的代码:currentPop = 312032486oneYear = 365hours = 24minutes = 60seconds = 60# seconds in a single daysecondsInDay = hours * minutes * seconds# seconds in a yearsecondsInYear = secondsInDay * oneYearfiveYears = secondsInYear * 5#Seconds in 5 yearsprint fiveYears# fiveYears in seconds, divided by 7 secondsbirths = fiveYears // 7print "If there was a birth every 7 seconds, there would be: " births "births"
查看完整描述

4 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

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


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

, in print功能将项目分隔为一个空格:


>>> 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


查看完整回答
反对 回复 2021-04-02
?
繁星coding

TA贡献1797条经验 获得超4个赞

Python是一种非常通用的语言。您可以通过不同的方法打印变量。我列出了以下五种方法。您可以根据需要使用它们。

例子:

a = 1b = 'ball'

方法1:

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

方法2:

print('I have', a, b)

方法3:

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

方法4:

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

方法5:

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

输出为:

I have 1 ball


查看完整回答
反对 回复 2021-04-02
?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

还有两个


第一个


>>> births = str(5)

>>> print("there are " + births + " births.")

there are 5 births.

添加字符串时,它们会串联在一起。


第二个


同样format,字符串的(Python 2.6和更高版本)方法可能是标准方法:


>>> births = str(5)

>>>

>>> print("there are {} births.".format(births))

there are 5 births.

此format方法也可以与列表一起使用


>>> format_list = ['five', 'three']

>>> # * unpacks the list:

>>> print("there are {} births and {} deaths".format(*format_list))  

there are five births and three deaths

或字典


>>> format_dictionary = {'births': 'five', 'deaths': 'three'}

>>> # ** unpacks the dictionary

>>> print("there are {births} births, and {deaths} deaths".format(**format_dictionary))

there are five births, and three deaths


查看完整回答
反对 回复 2021-04-02
  • 4 回答
  • 0 关注
  • 360 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号