Python 内建函数 - format(value[, format_spec])

  • Manual
  • 直译
  • 实例
  • 拓展阅读

Manual

Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

The default format_spec is an empty string which usually gives the same effect as calling str(value).

A call to format(value, format_spec) is translated to type(value).__format__(value, format_spec) which bypasses the instance dictionary when searching for the value’s __format__() method. A TypeError exception is raised if the method search reaches object and the format_spec is non-empty, or if either the format_spec or the return value are not strings.

Changed in version 3.4: object().__format__(format_spec) raises TypeError if format_spec is not an empty string.

直译

通过format_spec,将value转化为“格式化”的形式。format_spec的解析依赖于value参数的类型,无论如何,大多数内建类型通常使用一种标准格式化语法:Format Specification Mini-Language(格式化规范微语句)。
默认的format_spec是空字符串,通常与调用str(value)效果相同。
对format(value, format_spec)的调用被翻译为type(value),当搜索value的__format__()方法时,__format__(value, format_spec)会绕过实例字典。如果方法搜索到达对象层且format_spec非空,则会引发TypeError异常;或者如果format_spec或返回值不是字符串,也会引发同样的异常。
version 3.4变更: 如果format_spec为非空字符串,那么object().__format__(format_spec) 会引发TypeError。

实例

本实例引用自Python参考手册

# 通过位置访问参数
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 仅3.1+
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # 解包参数序列
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # 参数索引可以重复
'abracadabra'

#通过命名访问参数
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

#访问参数属性
>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} ''and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
        def __init__(self, x, y):
            self.x, self.y = x, y
        def __str__(self):
            return 'Point({self.x}, {self.y})'.format(self=self)

>>> str(Point(4, 2))
'Point(4, 2)'

#访问参数项
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

#用%s和%r替换
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

#...等等还有很多,详情见拓展阅读

拓展阅读

Format Specification Mini-Language(格式化规范微语句)

你可能感兴趣的:(Python笔录)