Python标准库:内置函数format(value[, format_spec])

的值的函数valueformat_spec的格式来格式化,然而函数解释format_spec是依据value的类型来决定的。不一样的类型有不一样的格式化解释。python

当參数format_spec为空时,本函数等同于函数str(value)的方式。函数

事实上本函数调用时,是把format(value, format_spec)的方式转换为type(value).__format__(format_spec)方式来调用。所以在value类型里就查找方法__format__(),假设找不到此方法,就会返回异常TypeError字体

当中format_spec的编写方式例如如下形式:spa

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]code

fill        ::=  <any character>orm

align       ::=  "<" | ">" | "=" | "^"blog

sign        ::=  "+" | "-" | " "ip

width       ::=  integerci

precision   ::=  integer博客

type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

fill是表示可以填写不论什么字符。

align是对齐方式,<是左对齐, >是右对齐。^是居中对齐。

sign是符号, +表示正号, -表示负号。

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

precision是小数保留位数。

type是输出数字值是的表示方式,比方b是二进制表示;比方E是指数表示。比方X是十六进制表示。

样例:

#format()

print(format(2918))
print(format(0x500, 'X'))
print(format(3.14, '0=10'))
print(format(3.14159, '05.3'))
print(format(3.14159, 'E'))
print(format('test', '<20'))
print(format('test', '>20'))
print(format('test', '^20'))

结果输出例如如下:

2918

500

0000003.14

03.14

3.141590E+00

test                

                test

        test        

 


蔡俊生  QQ:9073204 深圳

相关文章
相关标签/搜索