Python 字符串格式化操作


建議使用format()方法

字符串操作 對於 %, 官方以及給出這種格式化操作已經過時,在 Python 的未來版本中可能會消失。 在新代碼中使用新的字符串格式。因此推薦大家使用format()來替換 %.

format 方法系統複雜變量替換和格式化的能力,因此接下來看看都有哪些用法。

format()

這個方法是來自 string 模塊的Formatter類裡面的一個方法,屬於一個內置方法。因此可以在屬於 string 對象的範疇都可以調用這個方法。

語法結構

這個方法太強大了,官方的用戶是。

<code>replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | integer]
attribute_name ::= identifier
element_index ::= integer | index_string
index_string ::= +
conversion ::= "r" | "s" | "a"
format_spec ::= <described>
/<code>

針對 format_spec 的用法如下

<code>format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= /<code>

說明:

  • < 強制字段在可用空間內左對齊 > 強制字段在可用空間內右對齊 = 填充位於符號(如果有的話)之後,但位於數字之前 ^ 強制場位於可用空間的中心

常用的方法有下面幾個,format()方法中 的槽除了包括參數序號,還可以包括格式控制信息。此時,槽的內部樣式如下: 模板字符串>

{ : } 格式控制標記> 參數序號>

"{" *]["!" "r" | "s" | "a"] [":" format_spec] "}"

其中, 用來控制參數顯示時的格式,包括: ,<.> 6 個字段,這些字段都是可選的,可以組合使用,逐一介紹如下。 類型> 寬度> 對齊> 填充> 格式控制標記>


常用表達

  • 指定位置
<code>>>> '{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'/<code>

如果要顯示 { }

<code>>>> '{{}}, {}, {}'.format('b', 'c')
'{}, b, c'/<code>


  • 指定名稱
<code>>>> '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'/<code>


  • 指定屬性
    對於複數來說,有2個屬性。如果不知道屬性具體名字是什麼,可以用dir來查看。
<code>>>> c = 3-5j
>>> dir(c)
[....... 'imag', 'real']
>>> ('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)'/<code>
  • 訪問數組之類
<code>>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
'X: 3; Y: 5'/<code>
  • !s 區別 !r
<code>>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"/<code>


  • 文本對齊

下面文本居中和左有對齊

<code>>>> '{:<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***********'/<code>
  • 指定類型

b: 輸出整數的二進制方式;c: 輸出整數對應的 Unicode 字符;d: 輸出整數的十進制方式;o: 輸出整數的八進制方式;x: 輸出整數的小寫十六進制方式; X: 輸出整數的大寫十六進制方式;

<code>>>> '{:+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'/<code>


  • 逗號作為數千個分隔符:
<code>>>> '{:,}'.format(1234567890)
'1,234,567,890'/<code>


  • 表示百分比
<code>>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}.'.format(points/total)
'Correct answers: 86.36%'/<code>


  • 特定格式,比如日期
<code>>>> 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'/<code>


騷操作

可以用來輸出一個表格,有點類似三方庫prettytable的效果

<code>>>> width = 5
>>> for num in range(5,12):
... for base in 'dXob': # 分別為10/16/8/2進制
... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
... print()
...
5 5 5 101
6 6 6 110
7 7 7 111
8 8 10 1000

9 9 11 1001
10 A 12 1010
11 B 13 1011/<code>

高級用法 - 模板字符串

如果你是一個看Python語言工具的源碼的話,會發現這麼一個用法 - 模板字符串,比如robot裡面__init__.py裡面就有這麼一個用法。先看例子

<code>from string import Template

errorMessageTemplate = Template("""$reason
RIDE depends on wx (wxPython). .....""")

....

print(errorMessageTemplate.substitute(reason="wxPython not found."))/<code>

如果是有問題就會打印

<code>wxPython not found.
RIDE depends on wx (wxPython). ...../<code>

首先要導入模板Template,看看裡面有哪些屬性

<code>>>> from string import Template as t
>>> dir(t)
[.....'braceidpattern', 'delimiter', 'flags', 'idpattern', 'pattern', 'safe_substitute', 'substitute']

>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'


>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
[...]
ValueError: Invalid placeholder in string: line 1, col 10


>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):

[...]
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'/<code>


相關閱讀

https://stackoverflow.com/questions/5082452/string-formatting-vs-format

https://www.python.org/dev/peps/pep-3101

https://blog.csdn.net/i_chaoren/article/details/77922939

https://docs.python.org/release/3.1.5/library/stdtypes.html#old-string-formatting-operations

https://docs.python.org/release/3.1.5/library/string.html#string-formatting

看完了是不是對 format 已經有很深的認識了吧。趕緊動起來,實踐一下。


分享到:


相關文章: