访问次数
我的另一个总结性博客: todototry 大米粒

python字符串格式化方法 format函数的使用

 
python从2.6开始支持format,新的更加容易读懂的字符串格式化方法,
从原来的% 模式变成新的可读性更强的
  1. 花括号声明{}、用于渲染前的参数引用声明, 花括号里可以用数字代表引用参数的序号, 或者 变量名直接引用。
  2. 从format参数引入的变量名 、
  3. 冒号:、
  4. 字符位数声明、
  5. 空白自动填补符 的声明
  6. 千分位的声明
  7. 变量类型的声明: 字符串s、数字d、浮点数f
  8. 对齐方向符号 < ^ >
  9. 属性访问符中括号
  10. 使用惊叹号!后接a 、r、 s,声明 是使用何种模式, acsii模式、引用__repr__ 或 __str__
  11. 增加类魔法函数__format__(self, format) , 可以根据format前的字符串格式来定制不同的显示, 如: ’{:xxxx}’  此时xxxx会作为参数传入__format__函数中。 
 
 
综合举例说明:
  1. 如: 千分位、浮点数、填充字符、对齐的组合使用:
输入: '{:>18,.2f}'.format(70305084.0)     # :冒号+空白填充+右对齐+固定宽度18+浮点精度.2+浮点数声明f
输出:'     70,305,084.00'
 
  1. 复杂数据格式化
输入: data = [4, 8, 15, 16, 23, 42]
            '{d[4]} {d[5]}'.format(d=data)
输出: 23 42
 
  1. 复杂数据格式化:
输入: 
class Plant(object):
    type = 'tree'
    kinds = [{'name': 'oak'}, {'name': 'maple'}]

 
'{p.type}: {p.kinds[0][name]}'.format(p=Plant())
输出:tree: oak
 
 
 
 
 
分类举例说明:
 
  • 花括号声明{}、用于渲染前的参数引用声明, 花括号里可以用数字代表引用参数的序号, 或者 变量名直接引用。
        '{} {}'.format('one', 'two')
'{1} {0}'.format('one', 'two')
 
Output
two one
 
 
Setup
data = {'first': 'Hodor', 'last': 'Hodor!'}



Old

'%(first)s %(last)s' % data


New

'{first} {last}'.format(**data)


Output

Hodor Hodor!
 
 
 
  • 从format参数引入的变量名 、
 
  • 冒号:、字符位数声明、空白自动填补符 的声明、千分位的声明、变量类型的声明: 字符串s、数字d、浮点数f 、对齐方向符号 < ^ >
'{:.5}'.format('xylophone')


Output

xylop
        
'{:^10}'.format('test')


Output

   test   
 
'{:.{}}'.format('xylophone', 7)


Output

xylopho
'{:4d}'.format(42)


Output

  42
'{:06.2f}'.format(3.141592653589793)


Output

003.14
 
'{:+d}'.format(42)


Output

+42
 
千分位、浮点数、填充字符、对齐的组合使用:
 
输入: '{:>18,.2f}'.format(70305084.0)     # :冒号+空白填充+右对齐+固定宽度18+浮点精度.2+浮点数声明f
输出:'     70,305,084.00'
 
 
  • 属性访问符中括号

Setup

person = {'first': 'Jean-Luc', 'last': 'Picard'}


New

'{p[first]} {p[last]}'.format(p=person)


Output

Jean-Luc Picard

Setup

data = [4, 8, 15, 16, 23, 42]


New

'{d[4]} {d[5]}'.format(d=data)


Output

23 42
 

Setup

class Plant(object):
    type = 'tree'
    kinds = [{'name': 'oak'}, {'name': 'maple'}]


New

'{p.type}: {p.kinds[0][name]}'.format(p=Plant())


Output

tree: oak
 
 
  • 惊叹号!限定访问__repr__等魔法函数:

Setup

class Data(object):

    def __str__(self):
        return 'str'

    def __repr__(self):
        return 'repr'


Old

'%s %r' % (Data(), Data())


New

'{0!s} {0!r}'.format(Data())


Output

str repr
 
 
  • 增加类魔法函数__format__(self, format) , 可以根据format前的字符串格式来定制不同的显示, 如: ’{:xxxx}’  此时xxxx会作为参数传入__format__函数中。 

Setup

class HAL9000(object):

    def __format__(self, format):
        if (format == 'open-the-pod-bay-doors'):
            return "I'm afraid I can't do that."
        return 'HAL 9000'


New

'{:open-the-pod-bay-doors}'.format(HAL9000())


Output

I'm afraid I can't do that.
 
 
  • 时间日期的特例:

Setup

from datetime import datetime


New

'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))


Output

2001-02-03 04:05
 
 
 
 
 
 
posted @ 2016-07-02 18:47  fandyst  阅读(81144)  评论(2编辑  收藏  举报