Python 3.x 格式化输出字符串 % format 笔记
python格式化字符串有%和{}兩種 字符串格式控制符.
字符串輸入數(shù)據(jù)格式類型(%格式操作符號(hào))
%%百分號(hào)標(biāo)記
%c字符及其ASCII碼
%s字符串
%d有符號(hào)整數(shù)(十進(jìn)制)
%u無符號(hào)整數(shù)(十進(jìn)制)
%o無符號(hào)整數(shù)(八進(jìn)制)
%x無符號(hào)整數(shù)(十六進(jìn)制)
%X無符號(hào)整數(shù)(十六進(jìn)制大寫字符)
%e浮點(diǎn)數(shù)字(科學(xué)計(jì)數(shù)法)
%E浮點(diǎn)數(shù)字(科學(xué)計(jì)數(shù)法,用E代替e)
%f浮點(diǎn)數(shù)字(用小數(shù)點(diǎn)符號(hào))
%g浮點(diǎn)數(shù)字(根據(jù)值的大小采用%e或%f)
%G浮點(diǎn)數(shù)字(類似于%g)
%p指針(用十六進(jìn)制打印值的內(nèi)存地址)
%n存儲(chǔ)輸出字符的數(shù)量放進(jìn)參數(shù)列表的下一個(gè)變量中
?
字符串格式控制%[(name)][flag][width][.][precision]type
name:可為空,數(shù)字(占位),命名(傳遞參數(shù)名,不能以數(shù)字開頭)以字典格式映射格式化,其為鍵名
flag:標(biāo)記格式限定符號(hào),包含+-#和0,+表示右對(duì)齊(會(huì)顯示正負(fù)號(hào)),-左對(duì)齊,前面默認(rèn)為填充空格(即默認(rèn)右對(duì)齊),0表示填充0,#表示八進(jìn)制時(shí)前面補(bǔ)充0,16進(jìn)制數(shù)填充0x,二進(jìn)制填充0b
width:寬度(最短長(zhǎng)度,包含小數(shù)點(diǎn),小于width時(shí)會(huì)填充)
precision:小數(shù)點(diǎn)后的位數(shù),與C相同
type:輸入格式類型,請(qǐng)看上面
還有一種format_spec格式{[name][:][[fill]align][sign][#][0][width][,][.precision][type]}
用{}包裹name命名傳遞給format以命名=值?寫法,非字典映射,其他和上面相同
fill?=??<any?character> #fill是表示可以填寫任何字符
align =??"<"?|?">"?|?"="?|?"^" #align是對(duì)齊方式,<是左對(duì)齊,?>是右對(duì)齊,^是居中對(duì)齊。
sign? =??"+"?|?"-"?|?"?" #sign是符號(hào),?+表示正號(hào),?-表示負(fù)號(hào)
width =??integer #width是數(shù)字寬度,表示總共輸出多少位數(shù)字
precision =??integer #precision是小數(shù)保留位數(shù)
type =??"b"?|?"c"?|?"d"?|?"e"?|?"E"?|?"f"?|?"F"?|?"g"?|?"G"?|?"n"?|?"o"?|?"s"?|?"x"?|?"X"?|?"%" #type是輸出數(shù)字值是的表示方式,比如b是二進(jìn)制表示;比如E是指數(shù)表示;比如X是十六進(jìn)制表示
例子
1 print("{:,}".format(123456))#輸出1234,56 2 3 print("{a:w^8}".format(a="8"))#輸出www8wwww,填充w 4 5 print("%.5f" %5)#輸出5.000000 6 7 print("%-7s3" %("python"))#輸出python 3 8 9 print("%.3e" %2016)#輸出2.016e+03,也可以寫大E 10 11 print("%d %s" %(123456,"myblog"))#輸出123456 myblog 12 13 print("%(what)s is %(year)d" % {"what":"this year","year":2016})#輸出this year is 2016 14 15 print("{0}{1}".format("hello","fun"))#輸出hellofun,這與CSharp的格式化字符(占位符)相似 16 17 print("{}{}{}".format("spkk",".","cn"))#輸出spkk.cn 18 19 print("{a[0]}{a[1]}{a[2]}".format(a=["spkk",".","cn"]))#輸出spkk.cn 20 21 print("{dict[host]}{dict[dot]}{dict[domain]}".format(dict={"host":"www","domain":"spkk.cn","dot":"."}))#輸出www.spkk.cn 22 23 print("{a}{b}".format(a="python",b="3"))#輸出python3 24 25 print("{who} {doing} {0}".format("python",doing="like",who="I"))#輸出I like python?
轉(zhuǎn)載于:https://www.cnblogs.com/cnooye/p/5685670.html
總結(jié)
以上是生活随笔為你收集整理的Python 3.x 格式化输出字符串 % format 笔记的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android使用ImageLoader
- 下一篇: Python基础--列表