format 的用法
分类于:Python
发布于:2018-07-04
=> 基本语法
format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= digit+
grouping_option ::= "_" | ","
precision ::= digit+
type ::= "b"|"c"|"d"|"e"|"E"|"f"|"F"|"g"|"G"|"n"|"o"|"s"|"x"|"X"|"%"
=> 控制填充字符的转换方式
!r
和 !s
表示插入使用相应参数的 __repe__
和 __str__
函数得出的字符表示进行填充。
<<< "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
>>> "repr() shows quotes: 'test1'; str() doesn't: test2"
=> 对齐与填充
<<< '{:<30}'.format('left aligned')
'left aligned '
<<< '{:>30}'.format('right aligned')
' right aligned'
<<< '{:^30}'.format('centered')
' centered '
<<< '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'
=> 进制转换
<<< "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
# with 0x, 0o, or 0b as prefix:
<<< "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
=> 数值表示
<<< '{:,}'.format(1234567890)
'1,234,567,890'
=> 小数位数与百分比
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'
=> 格式化时间
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'