打印format

参考:https://www.cnblogs.com/lovejh/p/9201219.html

说明:

%和format:优先使用format.

format 方式在使用上较 % 操作符更为灵活。使用 format 方式时,参数的顺序与格式化的顺序不必完全相同

% 最终会被 .format 方式所代替。根据 Python 的官方文档,之所以仍然保留 % 操作符是为了保持向后兼容

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是十六进制表示

 

基本用法

 

# 不带字段
print('{} {}'.format('hello','world'))                #out:hello world
# 带数字编号
print('{0} {1}'.format('hello','world'))              #out:hello world
# 打乱顺序
print('{0} {1} {0}'.format('hello','world'))          #out:hello world hello 
print('{1} {1} {0}'.format('hello','world'))          #out:world world hello
# 带关键字
print('{a} {tom} {a}'.format(tom='hello',a='world'))  #out:world hello world  

 

原文地址:https://www.cnblogs.com/qianslup/p/12167309.html