Python_字符串格式化输出

 1. %

(1)通用格式:%[(name)][flags][width][.precision]typecode

  • (name)放置字典的键;flags有'+'(显示正负号),'-'(左对齐),'0'(补零)
  • width表示整体宽度;precision表示小数点后位数
  • 可以用*来指定width和precision

(2)格式符

格式符(typecode) 意义
s 字符串(或任何对象)
r s,但使用repr(输出带引号),而不是str
c ASCII码对应的字符
e 浮点指数(E,打印大写)
f,F 浮点十进制
g 浮点e或f(G,打印大写)
d 十进制(整数)
u 无符号(整数)
o,i,x 八进制,十进制,十六进制整数(X,打印大写)
% 转义,常量%

 

 

 

 

 

 

 

 

 

 

 

  

 

 

(3)例子

1 >>> "I'm %(name)s.I'm %(age)d years old." % {'name':'Bunny', 'age':20}
2 "I'm Bunny.I'm 20 years old."
3 >>> '%s--%r' % ('Hello','Hello')
4 "Hello--'Hello'"
5 >>> x = 1.23456
6 >>> '%+e...%-10.3E...%0*.*f' %(x, x, 8, 2, x)
7 '+1.234560e+00...1.235E+00 ...00001.23'

 

2. format

 (1)通用格式:{fieldname|conversionflag:[[fill]align][sign][#][0][width][.precision][typecode]}

  • fieldname可以是键或索引;conversionflag可以是r、s或a(repr, str, ascii)
  • fill是填充的字符,默认是空格
  • align有'<'(左对齐),'>'(右对齐),'^'(居中对齐),'='(只应用于数字,可用'>'代替)
  • sign有'+'(显示正负号),'-'(与不加'-'一致),空格(正数前面留空格);加#,会使输出带进制前缀
  • width和.precision之间可以加',',作为千位分隔符,表示金额

(2)格式符:与%格式化中的类似,区别在于多了'b'(二进制整数)和'%'(百分比),另外使用唯一的'd'表示十进制整数(而不是'i'或'u')

(3)例子

1 >>> "I'm {name}.I'm {info[age]} years old.".format(name='Bunny', info=dict(age=20))
2 "I'm Bunny.I'm 20 years old."
3 '{0:+<+8}...{0:>-08}...{0:0^ 8}...{1:=#8x}...{1:12,.2%}'.format(3.14, 100)
4 '+3.14+++...00003.14...0 3.1400...0x    64...  10,000.00%'

 时间格式化

1 >>> import datetime
2 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
3 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
4 '2010-07-04 12:15:58'

 

3. format的变形用法

1 >>> salary = 9999.99
2 >>> f'My salary is {salary:.0f}'
3 'My salary is 10000'

 

4. format_map

1 >>> student = {'name': '小明', 'class': '20190301', 'score': 597.5}
2 >>> '{st[class]}班{st[name]}总分:{st[score]}'.format(st=student)
3 '20190301班小明总分:597.5'
4 >>> '{class}班{name}总分:{score}'.format_map(student)
5 '20190301班小明总分:597.5'

 

posted @ 2020-03-06 14:12  亦示  阅读(383)  评论(0编辑  收藏  举报