Python基礎知識6:格式化字元、顏色
阿新 • • 發佈:2022-04-28
字元格式化,有兩種方式:
1、通過%佔位符方式,%s,%d,%
2、通過format,其中format比較好用,可以居中、可以用%、可以用二進位制、可以填充字元自定義;
1、利用%的案例
tp1="i am %s"%"aaa"# tp2="i am %s age %d"%("alex",18)#順序關聯 tp3="i am %(name)s age %(age)d"%{"name":"alex","age":18}#指定名稱,起名字 tp4="percent%.2f"%99.567#保留小數點幾位 tp5="i am %(pp).2f"%{"pp":12.45667,}#指定名稱,保留兩位小數 tp6="i am %(pp).2f%%"%{"pp":13.34566,}#用雙%%來引用% print("tp1:",tp1) print("tp2:",tp2) print("tp3:",tp3) print("tp4:",tp4) print("tp5:",tp5) print("tp6:",tp6)
執行結果:
2、利用format
tp1="i am {},age{},you are{}".format("hhh",123,"yyy")#順序填充 tp2="i am {},age{},you are{}".format(*["hhh",123,"yyy"])#動態引數填充 tp3="i am ,age,you are too".format("hhh",123)#佔位符索引填充,順序填充 tp4="i am ,age,you are too".format(*["hhh",123])#佔位符索引填充,動態引數填充 tp5="i am ,age,you are too".format(name="hhh",age=123)#指定名稱填充,名稱順序可變 tp6="i am ,age,you are too".format(**{"name":"hhh","age":123})#指定名稱,動態引數,字典需要** tp7="i am ,age,you are".format([1,2,3],[11,22,33])#通過列表傳遞 tp8="i am {:s},age{:d},money{:f}".format("hh",18,88.11)#格式化字元,S字元,d整數,f浮點型 tp9="i am ,age".format(name="hh",age=18)#指定名稱,S字元,d整數,f浮點型 tp10="i am ,age".format(**{"name":"hhh","age":123})#動態引數+指定名稱,S字元,d整數,f浮點型 tp11="numbers:{:b},{:o},{:d},{:x},{:X},{:%}".format(15,15,15,15,15,3.666)#格式化字元,b二進位制,d整型 tp12="numbers:,,,,,".format(15)#格式化+索引,b是位元組型,o是八進位制,x是16進位制 tp13="numbers:,,,,,".format(num=15)#格式化+指定名稱
執行結果:
tp1: i am hhh,age123,you areyyy tp2: i am hhh,age123,you areyyy tp3: i am hhh,age123,you arehhh too tp4: i am hhh,age123,you arehhh too tp5: i am hhh,age123,you arehhh too tp6: i am hhh,age123,you arehhh too tp7: i am 1,age2,you are3 tp8: i am hh,age18,money88.110000 tp9: i am hh,age18 tp10: i am hhh,age123 tp11: numbers:1111,17,15,f,F,366.600000% tp12: numbers:1111,17,15,f,F,1500.000000% tp13: numbers:1111,17,15,f,F,1500.000000%
顏色格式:
格式: echo "