python格式化字符串format函数

python格式化字符串format函数

1. format可以接受无限个的参数,位置可以不按顺序:

In [1]: "{} {}".format("hello","world") #不设定位置,按默认顺序
Out[1]: 'hello world'

In [2]: "{0} {1}".format("hello","world") #指定位置
Out[2]: 'hello world'

In [3]: "{1} {0} {1}".format("hello","world") #指定位置,重复使用参数
Out[3]: 'world hello world'

In [4]: "{name} {age}".format(name="Linda",age=15)#通过关键字
Out[4]: 'Linda 15'

# 通过字典设置参数
In [5]: info = {"name":"Linda","age":15}

In [6]: "{name} {age}".format(**info)
Out[6]: 'Linda 15'

# 通过列表设定参数
In [7]: my_list = ['hello','world']

In [8]: "{0[0]} {0[1]}".format(my_list)
Out[8]: 'hello world'

2. format格式控制:语法是{}中带冒号(:)

^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

+ 表示在正数前显示 +,负数前显示 -;  (空格)表示在正数前加空格

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

# 居中显示,长度度为4
In [9]: "{:^4}".format("he")
Out[9]: ' he '

# 左对齐,长度为4,空白地方填充"x"
In [10]: "{:x<4}".format("he")
Out[10]: 'hexx'

# 显示正负数符号
In [11]: "{:+}".format(-3)
Out[11]: '-3'

# 8的二进制显示
In [12]: "{:b}".format(8)
Out[12]: '1000'

# 用大括号{}转义大括号
In [13]: "{} is {{0}}".format("hello")
Out[13]: 'hello is {0}'