笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册
查看: 3072|回复: 0

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

[复制链接]

新手上路

Rank: 1

积分
3
发表于 2022-3-13 14:13:05 | 显示全部楼层 |阅读模式

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

语法

它通过{}和:来代替%

位置方法格式化
  1. >>> '{}.{}'.format('benniao365', 'com')
  2. 'benniao365.com'
  3. >>> '{}.{}.{}'.format('www', 'benniao365', 'com')
  4. 'www.benniao365.com'
  5. >>> '{1}.{2}'.format('www', 'benniao365', 'com')
  6. 'benniao365.com'
  7. >>> '{1}.{2} | {0}.{1}.{2}'.format('www', 'benniao365', 'com')
  8. 'benniao365.com | www.benniao365.com'
复制代码

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

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

通过关键字参数
  1. >>> '{domain}, {year}'.format(domain='www.benniao365.com', year=2016)
  2. 'www.benniao365.com, 2016'
  3. >>> '{domain} ### {year}'.format(domain='www.benniao365.com', year=2016)
  4. 'www.benniao365.com ### 2016'
  5. >>> '{domain} ### {year}'.format(year=2016,domain='www.benniao365.com')
  6. 'www.benniao365.com ### 2016'
复制代码
通过对象属性
  1. >>> class website:
  2.         def __init__(self,name,type):
  3.             self.name,self.type = name,type
  4.         def __str__(self):
  5.           return 'Website name: {self.name}, Website type: {self.type} '.format(self=self)
  6. >>> print str(website('benniao365.com', 'python'))
  7. Website name: benniao365.com, Website type: python
  8. >>> print website('benniao365.com', 'python')
  9. Website name: benniao365.com, Website type: python
复制代码
通过下标
  1. >>> '{0[1]}.{0[0]}.{1}'.format(['benniao365', 'www'], 'com')
  2. 'www.benniao365.com'
复制代码
有了这些便捷的“映射”方式,我们就有了偷懒利器。基本的python知识告诉我们,list和tuple可以通过“打散”成普通参数给函数,而dict可以打散成关键字参数给函数(通过和*)。所以可以轻松的传个list/tuple/dict给format函数, 非常灵活。
格式限定符

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

填充与对齐

填充常跟对齐一起使用

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

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


代码实例:

  1. >>> '{:>10}'.format(2016)
  2. '      2016'
  3. >>> '{:#>10}'.format(2016)
  4. '######2016'
  5. >>> '{:0>10}'.format(2016)
  6. '0000002016'
复制代码

数字精度与类型f

精度常跟类型f一起使用

  1. >>> '{:.2f}'.format(2016.0721)
  2. '2016.07'
复制代码

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

其他类型

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

  1. >>> '{:b}'.format(2016)
  2. '11111100000'
  3. >>> '{:d}'.format(2016)
  4. '2016'
  5. >>> '{:o}'.format(2016)
  6. '3740'
  7. >>> '{:x}'.format(2016)
  8. '7e0'
  9. >>>
复制代码

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

  1. >>> '{:,}'.format(20160721)
  2. '20,160,721'
复制代码

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



回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-7-27 12:43 , Processed in 0.671007 second(s), 18 queries .

© 2001-2020

快速回复 返回顶部 返回列表