天天看點

Pyhon程式設計:format格式化字元串代碼示例

基本格式

{name: format_spec}      

一般格式

[fill, align, sign, 0, width, .precision, type]      

可選參數說明

fill:是一個可選的填充字元,用于填充空白,預設為空格;
align,對齊方式.<,>,^分别代表左,右,居中對齊,預設為右對齊;
sign,取值為: 
    +,所有數字簽名都要加上符号;
    -,預設值,隻在負數簽名加符号;
    空格,在正數前面加上一個空格;
0,在寬度前面加0表示用0來填充數值前面的空白;
width,寬度;
.precision,精度的位數;
type,資料類型,如d(整數),s(字元串)等      

代碼示例

# -*- coding: utf-8 -*-

# 格式化
print("hello {}".format("world"))
print("hello {0}".format("world"))
print("hello {name}".format(name="world"))
"""
hello world
hello world
hello world
"""

# 對齊
print("hello |{:^20}|".format("world"))
print("hello |{:<20}|".format("world"))
print("hello |{:>20}|".format("world"))
print("hello |{:*>20}|".format("world"))
print("hello |{:&>20}|".format("world"))
"""
hello |       world        |
hello |world               |
hello |               world|
hello |***************world|
hello |&&&&&&&&&&&&&&&world|
"""

# 精度保留
print("{:.2f}".format(3.14159))
print("{:.4f}".format(3.1))
"""
3.14
3.1000
"""

# 進制轉化
print("{:b}".format(16))  # 二進制
print("{:o}".format(16))  # 八進制
print("{:d}".format(16))  # 十進制
print("{:x}".format(16))  # 十六進制
"""
10000
20
16
10
"""

# 千分位分隔符
print("{:,}".format(1000000))
print("{:,}".format(10000.123456))
"""
1,000,000
10,000.123456
"""

# 用=來填充,右對齊,因為已經用=來填充了,0無效,寬度11,小數點精度後精度為3,類型為浮點數
print "{0:=>+011.3f}".format(12.12345)
# ====+12.123      

參考

  1. python中format函數
  2. Python中的format()函數