建議使用format()方法
字串操作 對于 %, 官方以及給出這種格式化操作已經過時,在 Python 的未來版本中可能會消失, 在新代碼中使用新的字串格式,因此推薦大家使用format()來替換 %.
format 方法系統復雜變數替換和格式化的能力,因此接下來看看都有哪些用法,
format()
這個方法是來自 string 模塊的Formatter類里面的一個方法,屬于一個內置方法,因此可以在屬于 string 物件的范疇都可以呼叫這個方法,
語法結構
這個方法太強大了,官方的用戶是,
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 ::= <any source character except "]"> +
conversion ::= "r" | "s" | "a"
format_spec ::= <described in the next section>
針對 format_spec 的用法如下
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <a character other than '}'>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
說明:
<強制欄位在可用空間內左對齊>強制欄位在可用空間內右對齊=填充位于符號(如果有的話)之后,但位于數字之前^強制場位于可用空間的中心
常用的方法有下面幾個,format()方法中<模板字串>的槽除了包括引數序號,還可以包括格式控制資訊,此時,槽的內部樣式如下:
{<引數序號>: <格式控制標記>}
"{" [[identifier | integer]("." identifier | "[" integer | index_string "]")*]["!" "r" | "s" | "a"] [":" format_spec] "}"
其中,<格式控制標記>用來控制引數顯示時的格式,包括:<填充><對齊><寬度>,<.精度><型別>6 個欄位,這些欄位都是可選的,可以組合使用,逐一介紹如下,
常用表達
- 指定位置
>>> '{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'
如果要顯示 { }
>>> '{{}}, {}, {}'.format('b', 'c')
'{}, b, c'
- 指定名稱
>>> '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'
- 指定屬性
對于復數來說,有2個屬性,如果不知道屬性具體名字是什么,可以用dir來查看,
>>> 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)'
- 訪問陣列之類
>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
'X: 3; Y: 5'
- !s 區別 !r
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
- 文本對齊
下面文本居中和左有對齊
>>> '{:<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***********'
- 指定型別
b: 輸出整數的二進制方式;
c: 輸出整數對應的 Unicode 字符;
d: 輸出整數的十進制方式;
o: 輸出整數的八進制方式;
x: 輸出整數的小寫十六進制方式;
X: 輸出整數的大寫十六進制方式;
>>> '{:+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(1234567890)
'1,234,567,890'
- 表示百分比
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}.'.format(points/total)
'Correct answers: 86.36%'
- 特定格式,比如日期
>>> 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'
騷操作
可以用來輸出一個表格,有點類似三方庫prettytable的效果
>>> 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
高級用法 - 模板字串
如果你是一個看Python語言工具的原始碼的話,會發現這么一個用法 - 模板字串,比如robot里面__init__.py里面就有這么一個用法,先看例子
from string import Template
errorMessageTemplate = Template("""$reason
RIDE depends on wx (wxPython). .....""")
....
print(errorMessageTemplate.substitute(reason="wxPython not found."))
如果是有問題就會列印
wxPython not found.
RIDE depends on wx (wxPython). .....
首先要匯入模板Template,看看里面有哪些屬性
>>> 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'
相關閱讀
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 已經有很深的認識了吧,趕緊動起來,實踐一下,
Hi,Sup,如果覺得我寫的不錯,不妨幫個忙
1、可以關注我的公眾號「程式員匯聚地」,每天分享互聯網前沿技術,讓你的瑣碎時間不在無聊,聽說關注了的人越來越優秀,
2、順手點個贊唄,可以讓更多的人看到這篇文章,順便激勵下我,嘻嘻,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/204724.html
標籤:Python
下一篇:Java從零進階自學路線圖

