神一般的 str.format() 函数 - Python 字符串格式化转换(转载)

神一般的 str.format() 函数 - Python 字符串格式化转换

Myriad Record 2015-08-13 2139 阅读

不看不知道,一看吓一跳,简直 Godlike 了。str.format()真心非非非常好用。
但是话又说回来,Python 自带了相当多的好用功能,看得眼花缭乱。但是字符串格式化的就有三种:

  1. "%"操作符
  2. string.Template module
  3. str.format( *args , **kwargs ) function
  4. built-in 的format()函数

对新人来说真的有点迷糊 T.T


这里只摘录官方的例子,更详细的说明请参考官方文档:

https://docs.python.org/3/library/string.html#formatstrings

在大多数时候,str.format()函数与以前的"%"操作符相似。str.format()函数用"{}"和":"代替了以前的"%."符号。

通过位置匹配参数

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'

注意:{}占位符只有在Python2.7+有效,不能为空。代码注释中的 "# 3.1+ only"可能是官方忘记更新文档了。

从上面例子可以看到,{}可以为空(Python2.7+),也可以手动指定数序,同一个序号可以重复出现,可以不按顺序指定。

通过名称匹配参数

>>> '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'

可以指定转化

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

官方文档的占位符语法指出:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"

conversion ::= "r" | "s" | "a"

这里只有三个转换符号,用"!"开头。

"!r"对应 repr();"!s"对应 str(); "!a"对应ascii()。

字符串对齐并且指定对齐宽度

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'

另外,还有一个"="对齐符号,作用是:Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.

指定符号显示

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'

指定进制

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

使用","作用千位分隔符

>>> '{:,}'.format(1234567890)
'1,234,567,890'

百分数显示

>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'

事实上,我们有更多的类型符号

type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

每个符号的意义请参考官方文档。

type-specific formatting(不会翻译= =)

>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

占位符嵌套

这个 Trick 超级有用!

>>> for align, text in zip('<^>', ['left', 'center', 'right']):
...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'
>>> int(_, 16)
235521
>>>
>>> width = 5
>>> for num in range(5,12): 
...     for base in 'dXob':
...         print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
...     print()
...
     5     5   101
     6     6   110
     7     7   111
     8    10  1000
     9    11  1001
     A    12  1010
     B    13  1011

Python 官方文档中,有个概念叫"Format Specification Mini-Language",显然这是一种专门用于格式化表示迷你语言。编译原理的知识能对你理解这部分有一丢丢的帮助。

参考:

PEP 3101 -- Advanced String Formatting

Format Specification Mini-Language

Format String Syntax

神一般的 str.format() 函数 - Python 字符串格式化转换,首发于 IMLC.ME

原文:http://ju.outofmemory.cn/entry/198922
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值