首页 > 代码库 > python内置函数5-format()

python内置函数5-format()

Help on built-in function format in module __builtin__:


format(...)

    format(value[, format_spec]) -> string

    

    Returns value.__format__(format_spec)

    format_spec defaults to ""


format(value[, format_spec])

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.


Note format(value, format_spec) merely calls value.__format__(format_spec).


中文说明:

格式化字符串


通过位置

>>> ‘{0},{1}‘.format(‘kzc‘,18)

‘kzc,18‘

>>> ‘{1},{0}‘.format(‘kzc‘,18)

‘18,kzc‘

>>> ‘{},{}‘.format(‘kzc‘,18)

‘kzc,18‘

>>> ‘{0},{1},{1}‘.format(‘kzc‘,18)

‘kzc,18,18‘


通过关键字参数

>>> ‘{name},{age}‘.format(age=18,name=‘kzc‘)

‘kzc,18‘


通过对象属性

>>> class Person:

...     def __init__(self,name,age):

...             self.name,self.age = name,age

...             def __str__(self):

...                     return ‘This guy is {self.name},is {self.age} old‘.format(self=self)

... 

>>> str(Person(‘kzc‘,18))

‘This guy is kzc,is 18 old‘


通过下标

>>> p=[‘kzc‘,18]

>>> ‘{0[0]},{0[1]}‘.format(p)

‘kzc,18‘


填充与对齐

^、<、>分别是居中、左对齐、右对齐,后面带宽度

:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充

>>> ‘{:>8}‘.format(‘732‘)

‘     732‘

>>> ‘{:6>8}‘.format(‘732‘)

‘66666732‘

>>> ‘{:a<8}‘.format(‘732‘)

‘732aaaaa‘


精度与类型f

>>> ‘{:.2f}‘.format(435.62882)

‘435.63‘

>>> ‘{:b}‘.format(67)

‘1000011‘

>>> ‘{:d}‘.format(67)

‘67‘

>>> ‘{:o}‘.format(67)

‘103‘

>>> ‘{:x}‘.format(67)

‘43‘

>>> ‘{:,}‘.format(543721318713)

‘543,721,318,713‘


本文出自 “大云技术” 博客,请务必保留此出处http://hdlptz.blog.51cto.com/12553181/1900138

python内置函数5-format()