如何在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"


qq_笑_17
浏览 361回答 4
4回答

眼眸繁星

使用,分隔字符串和变量,同时打印: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

繁星coding

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

泛舟湖上清波郎朗

还有两个第一个>>> 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python