(二)format函数 (1)通过位置 print( '{0},{1}'.format('chuhao',20)) # chuhao,20 print('{},{}'.format('chuhao',20)) # chuhao,20 print('{1},{0},{1}'.format('chuhao',20)) # 20,chuhao,20 (2)通过关键字参数 print('{name},{age}'.format(age=18,name='chuhao')) # chuhao,18 (3)通过映射 list listvar = ['chuhao',20] lis = ['China','France'] print('my name is {0[0]},from {1[1]},age is {0[1]}'.format(listvar,lis)) # my name is chuhao,from France,age is 20 (4)通过映射 dict dictvar = {'name':'chuhao','age':20,'province':'shanxi'} print('my name is {name}, age is {age},from {province}'.format(**dictvar)) # my name is chuhao, age is 20,from shanxi (5)填充与对齐 print('{:>8}'.format('189')) # 189 占8个字符位,向右对齐 print('{:0>8}'.format('189')) # 00000189 占8个字符位,向右对齐,用0填充 print('{:a>8}'.format('189')) # aaaaa189 占8个字符位,向右对齐,用a填充 (6)精度与类型f print('{:.2f}'.format(321.33345)) # 321.33 保留两位小数 (7)用来做金额的千位分隔符 print('{:,}'.format(1234567890000)) # 1,234,567,890,000 (8)其他类型 主要就是进制,b、d、o、x分别是二进制、十进制、八进制、十六进制。 print('{:b}'.format(18)) # 二进制 10010 print('{:d}'.format(18)) # 十进制 18 print('{:o}'.format(18)) # 八进制 22 print('{:x}'.format(18)) # 十六进制12
转载于:https://www.cnblogs.com/lyj910313/p/10799683.html
相关资源:数据结构—成绩单生成器