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

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

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
添加回答
举报