天天看点

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()函数