python字符串格式化

%和转换符之间的修饰符

  • - ,左对齐标志,默认为右对齐
  • +,显示数值符号
  • 0,零填充
  • 一个指定最小宽度的数
  • .  一个小数点,后面跟位数(字符串最大个数,浮点之后的位数,整数最小位数
  • * 用于替换字段宽度
1 print('%*.*f' % (10, 2, 3.14159))
2 print('%.4s, %.5d, %.3f' % ('hello', 16, 3.14159))
3 print('%(key)010d, %(name)10s' % {'key':123, 'name':'Ron'})
4 
5 #vars()函数技巧
6 name = 'Ron'
7 age = 25
8 print('%(name)s is %(age)+d years old' % vars())

高级字符串格式化s.format

  • {n} n为整数:被位置参数代替
  • {name}:被关键字参数代替
  • {{}}:输出{}
  • {name[n]}:序列查找
  • {name[key]}:字典查找
  • {name.attr}:属性查找
  • {place:format_spec}:指定格式
    • [fill[align][sign][0][width][.precision][type]]
    • <,^,>:左中右对齐

 

 1 print("{0},{1},{0}".format('hello', 'world'))
 2 print("{name}, {age}".format(age=25, name='Ron'))
 3 print('{0}, {age}'.format('hello', age=22))
 4 print('{{hello}}, {}'.format(123))
 5 print('{name[1]}'.format(name=[1,2,3]))
 6 print('{name[key]}'.format(name={'key':'hello'}))
 7 print('{0.__doc__}'.format(str))
 8 print("{0.real} {0.imag}".format(3 + 4j))
 9 print("{name:>8},{age:*^8d}, {high:8.2f}".format(name='Ron', age=25, high=176.567))
10 
11 x = 42; y = 3.14159
12 print('{0:010b}'.format(x))
13 print('{0:010x}'.format(x))
14 print('{0:+010.2f}'.format(y))
15 print('{0:<+10.2%}'.format(y))
16 print('{0:{width}.{pre}f}'.format(y, width=10, pre=3))
17 print('{0!r:^20}'.format('Guido'))

 

posted @ 2018-06-08 23:34  Ron_White  阅读(187)  评论(0编辑  收藏  举报