前言
格式化字符串的函數(shù) str.format()
它增強了字符串格式化的功能。
通過用{} 和: 來代替 編程語言輸出中的%
代碼格式
1.默認輸出代碼方式
"{} {}".format("hello", "world")
輸出hello world
" { } “輸出{}內(nèi)的內(nèi)容以及” "內(nèi)的內(nèi)容,空格也會跟著輸出
2.指定位置的輸出
"{0},{1}".format("hello", "world")
輸出hello,world
3.指定多個位置輸出
"{1} {0} {1}".format("hello", "world")
輸出world hello world
4.字典中的調(diào)用參數(shù)設(shè)置
print("網(wǎng)站名:{name}, 地址 {url}".format(name="碼農(nóng)研究僧", url="https://blog.csdn.net/weixin_47872288"))
此處不能用0 或者1 代替name 以及url
5.列表的調(diào)用參數(shù)設(shè)置
"網(wǎng)站名:{0[0]}, 地址 {0[1]}".format('碼農(nóng)研究僧','https://blog.csdn.net/weixin_47872288')
此時輸出的是
如果列表這樣定義
則都是以數(shù)組0開頭
輸出全部結(jié)果
my_list = ['碼農(nóng)研究僧', 'https://blog.csdn.net/weixin_47872288']
print("網(wǎng)站名:{0[0]}, 地址 {0[1]}".format(my_list))
6.{}還可以放其他參數(shù)
{下標:輸出的格式}
例如:{:.2f} 保留小數(shù)點后兩位
{:+.2f} 帶符號保留小數(shù)點后兩位
{:,} 以逗號分隔的數(shù)字格式
{??} 以字符串格式輸出
。。。。等等
print("Output #14: {0:s}".format('I\'m enjoying learning Python.'))
7.輸出特殊字符
print("Output #14: {0:s}".format('I\'m enjoying learning Python.'))
使用單引號字符加轉(zhuǎn)義字符
如果是雙引號則不需要加
print("Output #14: {0:s}".format("I 'm enjoying learning Python."))
8.輸出多行字符串
使用 3 個單引號或者 3 個雙引號來創(chuàng)建多行字符串
print("Output #16: {0:s}".format('''You can use triple single quotes
for multi-line comment strings.'''))
9.其他文章來源:http://www.zghlxwxcb.cn/news/detail-403558.html
print(["{}".format(i) for i in range(5)])
結(jié)合列表格式的輸出文章來源地址http://www.zghlxwxcb.cn/news/detail-403558.html
實戰(zhàn)演練
x = 4
y = 5
z = x + y
print("Output #2: Four plus five equals {0:d},{0:d}.".format(z))
到了這里,關(guān)于python中format格式化函數(shù)(全)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!