新聞中心
python2.6 開始,新增了一種格式化字符串的函數(shù) str.format(),它增強(qiáng)了字符串格式化的功能。相對(duì)于老版的%格式方法,它有很多優(yōu)點(diǎn)。

1.在%方法中%s只能替代字符串類型,而在format中不需要理會(huì)數(shù)據(jù)類型;
2.單個(gè)參數(shù)可以多次輸出,參數(shù)順序可以不相同;
3.填充方式十分靈活,對(duì)齊方式十分強(qiáng)大;
4.官方推薦用的方式,%方式將會(huì)在后面的版本被淘汰。
相關(guān)推薦:《Python教程》
使用
1、按照默認(rèn)順序,不指定位置
print("{} {}".format("hello","world") )
hello world2、設(shè)置指定位置,可以多次使用
print("{0} {1} {0}".format("hello","or"))
hello or hello3、使用列表格式化
person = {"name":"opcai","age":20}
print("My name is {name} . I am {age} years old .".format(**person))
My name is opcai . I am 20 years old.4、通過列表格式化
stu = ["opcai","linux","MySQL","Python"]
print("My name is {0[0]} , I love {0[1]} !".format(stu))
My name is opcai , I love linux !數(shù)字格式化
數(shù)字 格式 輸出 描述
3.1415926 {:.2f} 3.14 保留小數(shù)點(diǎn)后兩位
3.1415926 {:+.2f} +3.14 帶符號(hào)保留小數(shù)點(diǎn)后兩位
-1 {:+.2f} -1.00 帶符號(hào)保留小數(shù)點(diǎn)后兩位
2.71828 {:.0f} 3 不帶小數(shù)
5 {:0>2d} 05 數(shù)字補(bǔ)零 (填充左邊, 寬度為2)
5 {:x<4d} 5xxx 數(shù)字補(bǔ)x (填充右邊, 寬度為4)
10 {:x<4d} 10xx 數(shù)字補(bǔ)x (填充右邊, 寬度為4)
1000000 {:,} 1,000,000 以逗號(hào)分隔的數(shù)字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指數(shù)記法
13 {:10d} 13 右對(duì)齊 (默認(rèn), 寬度為10)
13 {:<10d} 13 左對(duì)齊 (寬度為10)
13 {:^10d} 13 中間對(duì)齊 (寬度為10)
進(jìn)制轉(zhuǎn)換
11 '{:b}'.format(11) 1011 二進(jìn)制
11 '{:d}'.format(11) 11 十進(jìn)制
11 '{:o}'.format(11) 13 八進(jìn)制
11 '{:x}'.format(11) b 十六進(jìn)制
11 '{:#x}'.format(11) 0xb 十六進(jìn)制
11 '{:#X}'.format(11) 0XB 十六進(jìn)制
^, <, > 分別是居中、左對(duì)齊、右對(duì)齊,后面帶寬度, : 號(hào)后面帶填充的字符,只能是一個(gè)字符,不指定則默認(rèn)是用空格填充。
+ 表示在正數(shù)前顯示 +,負(fù)數(shù)前顯示 -; (空格)表示在正數(shù)前加空格。
b、d、o、x 分別是二進(jìn)制、十進(jìn)制、八進(jìn)制、十六進(jìn)制。
輸出大括號(hào)
print("{} {{0}}".format("opcai_linux"))
opcai_linux {0} 當(dāng)前題目:創(chuàng)新互聯(lián)Python教程:python為什么要字符串格式化
路徑分享:http://www.dlmjj.cn/article/dhjoogi.html


咨詢
建站咨詢
