python學習筆記8 format

2021-06-22 17:42:30 字數 2471 閱讀 7402

format()是python的內建函式,主要用來控制輸出的格式,format()函式返回的是乙個string。

format()函式的格式是

format_spec::=  [[fill]align][sign][#][0][width][,][.precision][type]

fill::=align::= "<" | ">" | "=" | "^"

sign::= "+" | "-" | " "

width::= integer

precision::= integer

type::= "b" | "c" | "d" | "e" | "e" | "f" | "f" | "g" | "g" | "n" | "o" | "s" | "x" | "x" | "%"

下面對其中比較常用的引數做簡單介紹:

[[fill]align]:選擇對齊方式與填充字元。align是對齊方式,數字型別的預設對齊方式是右對齊,string型別預設的對齊方式是左對齊;"<"代表左對齊,">"代表右對齊,"="代表符號(如果有,如+,-)左對齊,數字右對齊;"^"代表居中對齊;fill是填充字元,可選。舉個例子:

# align

print (format(12300,"<10d")) # 12300

print (format(12300,">10d")) # 12300

print (format(12300,"=+10d")) # + 12300

print (format(12300,"^10d")) # 12300

print (format(12300,"*^10d")) # **12300***

[sign]:數字型別時的正負符號,"+"表示不管數字是正還是負都加符號,"-"表示只有為負數時才加符號(預設)," "表示如果不為負數時,首字元空出,為負數時,首字元為負號;舉幾個例子:

# sign

print (format(12300,"<+10d")) # +12300

print (format(-12300,"<+10d")) # -12300

print (format(12300,"<-10d")) # 12300

print (format(-12300,"<-10d")) # -12300

print (format(12300,"< 10d")) # 12300

print (format(-12300,"< 10d")) # -12300

[width]:輸出的寬度,如上面的10,表示輸出10個字元寬度的大小,如果超出則以實際字元大小為準。

[precision]:通常用來對浮點型數字進行精度的擷取,預設大小是6,舉幾個例子:

# precision

print (format(58.56789,"<10.2f")) # 58.57

print (format(58.5678901234,"<10.3f"))# 58.568

print (format(58.1,"<10.4f")) # 58.1000

print (format(58,"<10.2f")) # 58.00

[type]:主要是根據不同的數字或字元型別進行格式化,其中"b"表示二進位制輸出,"c"表示將整型轉換成字元輸出,"d"表示十進位制輸出,"e"和"e"表示以科學法輸出(區別在於大小寫),"f"和"f"表示浮點型輸出,"g"和"g"表示去掉多餘的0,"o"表示八進位制輸出,"s"表示字串輸出,"x"和"x"表示十六進製制輸出,"%"表示百分比輸出,舉幾個例子:

# type

print (format(15,"<10d")) # 15

print (format(15,"<10b")) # 1111

print (format(78,"<10c")) # n

print (format(15,"<1e")) # 1.500000e+01

print (format(15,"<10.2f")) # 15.00

print (format(15.000,"<10g")) # 15

print (format(15,"<10o")) # 17

print (format(15,"<10x")) # f

print (format(0.15,"<10%")) # 15.000000%

format()函式的簡單介紹就到這裡,後續繼續學習~

form學習筆記

學習 html權威指南 學習筆記 配置表單 其他功能 form告訴瀏覽器它處理的是html表單 區域性屬性內容 習慣樣式form 設定表單外的元素 input 區域性屬性 內容 習慣樣式 button 區域性屬性 內容 習慣樣式 type屬性的值 如果不設定form元素的action屬性,則瀏覽器會...

python學習筆記8

主要講了python的輸入和輸出 python通過 python2.x raw input和 python3.x input來實現輸入輸出。input可以加引數,表示為提示符,返回值為你的輸入。比如 age input how old are you?print your age is s age ...

Python學習筆記8(類)

8.1 建立和使用類 class dog def init self,name,age 初始化屬性name和age self.name name self.age age defsit self 模擬小狗被命令石蹲下 print self.name is now sitting def roll s...