Python格式化输出字符串方法小结【%与format】

python格式化字符串有%和{}两种 字符串格式控制符.

字符串输入数据格式类型(%格式操作符号)

%% 百分号标记#就是输出一个%
%c 字符及其ASCII码
%s 字符串
%d 有符号整数(十进制)
%u 无符号整数(十进制)
%o 无符号整数(八进制)
%x 无符号整数(十六进制)
%X 无符号整数(十六进制大写字符)
%e 浮点数字(科学计数法)
%E 浮点数字(科学计数法,用E代替e)
%f 浮点数字(用小数点符号)
%g 浮点数字(根据值的大小采用%e或%f)
%G 浮点数字(类似于%g)
%p 指针(用十六进制打印值的内存地址)
%n 存储输出字符的数量放进参数列表的下一个变量中

字符串格式控制%[(name)][flag][width][.][precision]type
name:可为空,数字(占位),命名(传递参数名,不能以数字开头)以字典格式映射格式化,其为键名

flag:标记格式限定符号,包含+-#和0,+表示右对齐(会显示正负号),-左对齐,前面默认为填充空格(即默认右对齐),0表示填充0,#表示八进制时前面补充0,16进制数填充0x,二进制填充0b

width:宽度(最短长度,包含小数点,小于width时会填充)

precision:小数点后的位数,与C相同

type:输入格式类型,请看上面

还有一种format_spec格式{[name][:][[fill]align][sign][#][0][width][,][.precision][type]}
用{}包裹name命名传递给format以命名=值 写法,非字典映射,其他和上面相同

fill =  <any character>  #fill是表示可以填写任何字符

align =  "<" | ">" | "=" | "^"  #align是对齐方式,<是左对齐, >是右对齐,^是居中对齐。

sign  =  "+" | "-" | " "  #sign是符号, +表示正号, -表示负号

width =  integer  #width是数字宽度,表示总共输出多少位数字

precision =  integer  #precision是小数保留位数

type =  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"  #type是输出数字值是的表示方式,比如b是二进制表示;比如E是指数表示;比如X是十六进制表示

例子(本机测试运行环境:Python3.6)

>>> print("{:,}".format(123456))#输出1234,56
123,456
>>> print("{a:w^8}".format(a="8"))#输出www8wwww,填充w
www8wwww
>>> print("%.5f" %5)#输出5.000000
5.00000
>>> print("%-7s3" %("python"))#输出python 3
python 3
>>> print("%.3e" %2016)#输出2.016e+03,也可以写大E
2.016e+03
>>> print("%d %s" %(123456,"laike"))#输出123456 laike
123456 laike
>>> print("%(what)s is %(year)d" % {"what":"this year","year":2016})#输出this year is 2016
this year is 2016
>>> print("{0}{1}".format("hello","fun"))#输出hellofun,这与CSharp的格式化字符(占位符)相似
hellofun
>>> print("{}{}{}".format("laike",".","net"))#输出laike.net
laike.net
>>> print("{a[0]}{a[1]}{a[2]}".format(a=["laike",".","net"]))#输出laike.net
laike.net
>>> print("{dict[host]}{dict[dot]}{dict[domain]}".format(dict={"host":"www","domain":"laike.net","dot":"."}))#输出www.laike.net
www.laike.net
>>> print("{a}{b}".format(a="python",b="3"))#输出python3
python3
>>> print("{who} {doing} {0}".format("python",doing="like",who="I"))#输出I like python
I like python
>>>

另:关于Python format函数格式化输出操作可参考前面一篇Python字符串基本操作