python强大的字符串格式化函数 - format

高洛峰
Libérer: 2016-10-17 11:38:22
original
1174 Les gens l'ont consulté

自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足。那么,他跟之前的%型格式化字符串相比,有什么优越的存在呢?让我们来揭开它羞答答的面纱。

语法

它通过{}和:来代替%


位置方法格式化

>>> '{}.{}'.format('pythontab', 'com')
'pythontab.com'
>>> '{}.{}.{}'.format('www', 'pythontab', 'com')
'www.pythontab.com'
>>> '{1}.{2}'.format('www', 'pythontab', 'com')
'pythontab.com'
>>> '{1}.{2} | {0}.{1}.{2}'.format('www', 'pythontab', 'com')
'pythontab.com | www.pythontab.com'
Copier après la connexion

字符串的format函数可以接受不限个参数,参数位置可以不按顺序,参数可以不使用或者使用多次,非常灵活

注意: python2.6下不能为空{},python2.7以上版本可以。


通过关键字参数

>>> '{domain}, {year}'.format(domain='www.pythontab.com', year=2016)
'www.pythontab.com, 2016'
>>> '{domain} ### {year}'.format(domain='www.pythontab.com', year=2016)
'www.pythontab.com ### 2016'
>>> '{domain} ### {year}'.format(year=2016,domain='www.pythontab.com')
'www.pythontab.com ### 2016'
Copier après la connexion

通过对象属性

>>> class website: 
        def __init__(self,name,type): 
            self.name,self.type = name,type 
        def __str__(self): 
          return 'Website name: {self.name}, Website type: {self.type} '.format(self=self) 
>>> print str(website('pythontab.com', 'python'))
Website name: pythontab.com, Website type: python
>>> print website('pythontab.com', 'python')
Website name: pythontab.com, Website type: python
Copier après la connexion

通过下标

>>> '{0[1]}.{0[0]}.{1}'.format(['pyhtontab', 'www'], 'com')
'www.pyhtontab.com'
Copier après la connexion

有了这些便捷的“映射”方式,我们就有了偷懒利器。基本的python知识告诉我们,list和tuple可以通过“打散”成普通参数给函数,而dict可以打散成关键字参数给函数(通过和*)。所以可以轻松的传个list/tuple/dict给format函数, 非常灵活。


格式限定符

它有着丰富的的“格式限定符”(语法是{}中带:号),比如:

填充与对齐

填充常跟对齐一起使用

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

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


代码实例:

>>> &#39;{:>10}&#39;.format(2016)
&#39;      2016&#39;
>>> &#39;{:#>10}&#39;.format(2016)
&#39;######2016&#39;
>>> &#39;{:0>10}&#39;.format(2016)
&#39;0000002016&#39;
Copier après la connexion

数字精度与类型f

精度常跟类型f一起使用

>>> &#39;{:.2f}&#39;.format(2016.0721)
&#39;2016.07&#39;
Copier après la connexion

其中.2表示长度为2的精度,f表示float类型。

其他类型

主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。

>>> &#39;{:b}&#39;.format(2016)
&#39;11111100000&#39;
>>> &#39;{:d}&#39;.format(2016)
&#39;2016&#39;
>>> &#39;{:o}&#39;.format(2016)
&#39;3740&#39;
>>> &#39;{:x}&#39;.format(2016)
&#39;7e0&#39;
>>>
Copier après la connexion

用,号还能用来做金额的千位分隔符。

>>> &#39;{:,}&#39;.format(20160721)
&#39;20,160,721&#39;
Copier après la connexion

 format的功能太强大了, 还有很多功能, 大家可以去尝试一下。


source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!