4 回答

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
使用,分隔字符串和變量,同時(shí)打?。?/p>
print("If there was a birth every 7 seconds, there would be: ", births, "births")
, in print功能將項(xiàng)目分隔為一個(gè)空格:
>>> print("foo", "bar", "spam")
foo bar spam
或更好地使用字符串格式:
print("If there was a birth every 7 seconds, there would be: {} births".format(births))
字符串格式化功能更強(qiáng)大,它還允許您執(zhí)行其他操作,例如填充,填充,對(duì)齊,寬度,設(shè)置精度等。
>>> 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貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
Python是一種非常通用的語(yǔ)言。您可以通過不同的方法打印變量。我列出了以下五種方法。您可以根據(jù)需要使用它們。
例子:
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} ')
輸出為:
I have 1 ball

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
還有兩個(gè)
第一個(gè)
>>> births = str(5)
>>> print("there are " + births + " births.")
there are 5 births.
添加字符串時(shí),它們會(huì)串聯(lián)在一起。
第二個(gè)
同樣format,字符串的(Python 2.6和更高版本)方法可能是標(biāo)準(zhǔn)方法:
>>> 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
添加回答
舉報(bào)