python format

来源:互联网 发布:head first java 烂 编辑:程序博客网 时间:2024/05/21 08:44

python format

python自2.6后,新增了一种格式化字符串函数str.format(),威力十足,可以替换掉原来的%

:以下操作版本是python2.7

映射示例

回到顶部

语法

通过{} 和 :  替换 %

回到顶部

通过位置

>>> '{0} is {1}'.format('jihite', '4 years old')'jihite is 4 years old'>>> '{0} is {1} {0}'.format('jihite', '4 years old')'jihite is 4 years old jihite'

通过format函数可以接受不限参数个数、不限顺序

回到顶部

通过关键字

>>> '{name}:{age}'.format(age=4,name='jihite')'jihite:4'>>> '{name}:{age}'.format(age=4,name='jihite',locate='Beijing')'jihite:4'

format括号内用=给变量赋值

回到顶部

通过对象属性

复制代码
>>> class Person:...     def __init__(self, name, age):...         self.name,self.age = name, age...     def __func__(self):...         return "This guy is {self.name}, is {self.age} old".format(self=self)... >>> s =Person('jihite', 4)>>> s.__func__()'This guy is jihite, is 4 old'
复制代码
回到顶部

通过下标

>>> '{0[0]} is {0[1]} years old!'.format(['jihite', 4])'jihite is 4 years old!'>>> '{0} is {1} years old!'.format('jihite', 4)'jihite is 4 years old!'

其实就是通过位置

格式限定符

通过{} : 符号

回到顶部

填充和对齐

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

复制代码
>>> '{:>10}'.format('jihite')'    jihite'>>> '{:<10}'.format('jihite')'jihite    '>>> '{:^10}'.format('jihite')'  jihite  '
复制代码
回到顶部

精度和类型f

精度常和f一起使用

>>> '{:.2f}'.format(3.1415)'3.14'>>> '{:.4f}'.format(3.1)'3.1000'
回到顶部

进制转化

复制代码
>>> '{:b}'.format(10)'1010'>>> '{:o}'.format(10)'12'>>> '{:d}'.format(10)'10'>>> '{:x}'.format(10)'a'
复制代码

其中b o d x分别表示二、八、十、十六进制

回到顶部

千位分隔符

复制代码
>>> '{:,}'.format(1000000)'1,000,000'

  >>> '{:,}'.format(100000.23433)
  '100,000.23433'

>>> '{:,}'.format('abcedef')Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: Cannot specify ',' with 's'.
复制代码

这种情况只针对数字



1、使用位置参数

要点:从以下例子可以看出位置参数不受顺序约束,且可以为{},只要format里有相对应的参数值即可,参数索引从0开,传入位置参数列表可用*列表

复制代码
>>> li = ['hoho',18]>>> 'my name is {} ,age {}'.format('hoho',18)'my name is hoho ,age 18'>>> 'my name is {1} ,age {0}'.format(10,'hoho')'my name is hoho ,age 10'>>> 'my name is {1} ,age {0} {1}'.format(10,'hoho')'my name is hoho ,age 10 hoho'>>> 'my name is {} ,age {}'.format(*li)'my name is hoho ,age 18'
复制代码

 

2、使用关键字参数

要点:关键字参数值要对得上,可用字典当关键字参数传入值,字典前加**即可

>>> hash = {'name':'hoho','age':18}>>> 'my name is {name},age is {age}'.format(name='hoho',age=19)'my name is hoho,age is 19'>>> 'my name is {name},age is {age}'.format(**hash)'my name is hoho,age is 18'

 

3、填充与格式化

:[填充字符][对齐方式 <^>][宽度]

>>> '{0:*>10}'.format(10)  ##右对齐'********10'>>> '{0:*<10}'.format(10)  ##左对齐'10********'>>> '{0:*^10}'.format(10)  ##居中对齐'****10****'

 

4、精度与进制

复制代码
>>> '{0:.2f}'.format(1/3)'0.33'>>> '{0:b}'.format(10)    #二进制'1010'>>> '{0:o}'.format(10)     #八进制'12'>>> '{0:x}'.format(10)     #16进制'a'>>> '{:,}'.format(12369132698)  #千分位格式化'12,369,132,698'
复制代码

 

5、使用索引

>>> li['hoho', 18]>>> 'name is {0[0]} age is {0[1]}'.format(li)'name is hoho age is 18