簡介
f-string,亦稱為格式化字符串常量(formatted string literals),是Python3.6新引入的一種字符串格式化方法,該方法源於PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加簡便。f-string在形式上是以 f 或 F 修飾符引領的字符串(f'xxx' 或 F'xxx'),以大括號 {} 標明被替換的字段;f-string在本質上並不是字符串常量,而是一個在運行時運算求值的表達式:
While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
(與具有恆定值的其它字符串常量不同,格式化字符串實際上是運行時運算求值的表達式。)
—— Python Documentation
f-string在功能方面不遜於傳統的%-formatting語句和str.format()函數,同時性能又優於二者,且使用起來也更加簡潔明了,因此對於Python3.6及以后的版本,推薦使用f-string進行字符串格式化。
用法
此部分內容主要參考以下資料:
Python Documentation – Formatted String Literals
Python Documentation – Format String Syntax
PEP 498 – Literal String Interpolation
Python 3’s f-Strings: An Improved String Formatting Syntax (Guide)
python3 f-string格式化字符串的高級用法
Python 3: An Intro to f-strings
簡單使用
f-string用大括號 {} 表示被替換字段,其中直接填入替換內容:
>>> name = 'Eric'
>>> f'Hello, my name is {name}'
'Hello, my name is Eric'
>>> number = 7
>>> f'My lucky number is {number}'
'My lucky number is 7'
>>> price = 19.99
>>> f'The price of this book is {price}'
'The price of this book is 19.99'
表達式求值與函數調用
f-string的大括號 {} 可以填入表達式或調用函數,Python會求出其結果並填入返回的字符串內:
>>> f'A total number of {24 * 8 + 4}'
'A total number of 196'
>>> f'Complex number {(2 + 2j) / (2 - 3j)}'
'Complex number (-0.15384615384615388+0.7692307692307692j)'
>>> name = 'ERIC'
>>> f'My name is {name.lower()}'
'My name is eric'
>>> import math
>>> f'The answer is {math.log(math.pi)}'
'The answer is 1.1447298858494002'
引號、大括號與反斜杠
f-string大括號內所用的引號不能和大括號外的引號定界符沖突,可根據情況靈活切換 ' 和 ":
>>> f'I am {"Eric"}'
'I am Eric'
>>> f'I am {'Eric'}'
File "<stdin>", line 1
f'I am {'Eric'}'
^
SyntaxError: invalid syntax
若 ' 和 " 不足以滿足要求,還可以使用 ''' 和 """:
>>> f"He said {"I'm Eric"}"
File "<stdin>", line 1
f"He said {"I'm Eric"}"
^
SyntaxError: invalid syntax
>>> f'He said {"I'm Eric"}'
File "<stdin>", line 1
f'He said {"I'm Eric"}'
^
SyntaxError: invalid syntax
>>> f"""He said {"I'm Eric"}"""
"He said I'm Eric"
>>> f'''He said {"I'm Eric"}'''
"He said I'm Eric"
大括號外的引號還可以使用 \ 轉義,但大括號內不能使用 \ 轉義:
>>> f'''He\'ll say {"I'm Eric"}'''
"He'll say I'm Eric"
>>> f'''He'll say {"I\'m Eric"}'''
File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
1
2
3
4
5
f-string大括號外如果需要顯示大括號,則應輸入連續兩個大括號 {{ 和 }}:
>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}'
'{5} stars'
上面提到,f-string大括號內不能使用 \ 轉義,事實上不僅如此,f-string大括號內根本就不允許出現 \。如果確實需要 \,則應首先將包含 \ 的內容用一個變量表示,再在f-string大括號內填入變量名:
>>> f"newline: {ord('\n')}"
File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
>>> newline = ord('\n')
>>> f'newline: {newline}'
'newline: 10'
多行f-string
f-string還可用於多行字符串:
>>> name = 'Eric'
>>> age = 27
>>> f"Hello!" \
... f"I'm {name}." \
... f"I'm {age}."
"Hello!I'm Eric.I'm 27."
>>> f"""Hello!
... I'm {name}.
... I'm {age}."""
"Hello!\n I'm Eric.\n I'm 27."
自定義格式:對齊、寬度、符號、補零、精度、進制等
f-string采用 {content:format} 設置字符串格式,其中 content 是替換並填入字符串的內容,可以是變量、表達式或函數等,format 是格式描述符。采用默認格式時不必指定 {:format},如上面例子所示只寫 {content} 即可。
關於格式描述符的詳細語法及含義可查閱Python官方文檔,這里按使用時的先后順序簡要介紹常用格式描述符的含義與作用:
對齊相關格式描述符
格式描述符含義與作用
<左對齊(字符串默認對齊方式)
>右對齊(數值默認對齊方式)
^居中
數字符號相關格式描述符
格式描述符含義與作用
+負數前加負號(-),正數前加正號(+)
-負數前加負號(-),正數前不加任何符號(默認)
(空格)負數前加負號(-),正數前加一個空格
注:僅適用於數值類型。
數字顯示方式相關格式描述符
格式描述符含義與作用
#切換數字顯示方式
注1:僅適用於數值類型。
注2:# 對不同數值類型的作用效果不同,詳見下表:
數值類型不加#(默認)加#區別
二進制整數'1111011''0b1111011'開頭是否顯示 0b
八進制整數'173''0o173'開頭是否顯示 0o
十進制整數'123''123'無區別
十六進制整數(小寫字母)'7b''0x7b'開頭是否顯示 0x
十六進制整數(大寫字母)'7B''0X7B'開頭是否顯示 0X
寬度與精度相關格式描述符
格式描述符含義與作用
width整數 width 指定寬度
0width整數 width 指定寬度,開頭的 0 指定高位用 0 補足寬度
width.precision整數 width 指定寬度,整數 precision 指定顯示精度
注1:0width 不可用於復數類型和非數值類型,width.precision 不可用於整數類型。
注2:width.precision 用於不同格式類型的浮點數、復數時的含義也不同:用於 f、F、e、E 和 % 時 precision 指定的是小數點后的位數,用於 g 和 G 時 precision 指定的是有效數字位數(小數點前位數+小數點后位數)。
注3:width.precision 除浮點數、復數外還可用於字符串,此時 precision 含義是只使用字符串中前 precision 位字符。
示例:
>>> a = 123.456
>>> f'a is {a:8.2f}'
'a is 123.46'
>>> f'a is {a:08.2f}'
'a is 00123.46'
>>> f'a is {a:8.2e}'
'a is 1.23e+02'
>>> f'a is {a:8.2%}'
'a is 12345.60%'
>>> f'a is {a:8.2g}'
'a is 1.2e+02'
>>> s = 'hello'
>>> f's is {s:8s}'
's is hello '
>>> f's is {s:8.3s}'
's is hel '
千位分隔符相關格式描述符
格式描述符含義與作用
,使用,作為千位分隔符
_使用_作為千位分隔符
注1:若不指定 , 或 _,則f-string不使用任何千位分隔符,此為默認設置。
注2:, 僅適用於浮點數、復數與十進制整數:對於浮點數和復數,, 只分隔小數點前的數位。
注3:_ 適用於浮點數、復數與二、八、十、十六進制整數:對於浮點數和復數,_ 只分隔小數點前的數位;對於二、八、十六進制整數,固定從低位到高位每隔四位插入一個 _(十進制整數是每隔三位插入一個 _)。
示例:
>>> a = 1234567890.098765
>>> f'a is {a:f}'
'a is 1234567890.098765'
>>> f'a is {a:,f}'
'a is 1,234,567,890.098765'
>>> f'a is {a:_f}'
'a is 1_234_567_890.098765'
>>> b = 1234567890
>>> f'b is {b:_b}'
'b is 100_1001_1001_0110_0000_0010_1101_0010'
>>> f'b is {b:_o}'
'b is 111_4540_1322'
>>> f'b is {b:_d}'
'b is 1_234_567_890'
>>> f'b is {b:_x}'
'b is 4996_02d2'
格式類型相關格式描述符
基本格式類型
格式描述符含義與作用適用變量類型
s普通字符串格式字符串
b二進制整數格式整數
c字符格式,按unicode編碼將整數轉換為對應字符整數
d十進制整數格式整數
o八進制整數格式整數
x十六進制整數格式(小寫字母)整數
X十六進制整數格式(大寫字母)整數
e科學計數格式,以 e 表示 ×10^浮點數、復數、整數(自動轉換為浮點數)
E與 e 等價,但以 E 表示 ×10^浮點數、復數、整數(自動轉換為浮點數)
f定點數格式,默認精度(precision)是6浮點數、復數、整數(自動轉換為浮點數)
F與 f 等價,但將 nan 和 inf 換成 NAN 和 INF浮點數、復數、整數(自動轉換為浮點數)
g通用格式,小數用 f,大數用 e浮點數、復數、整數(自動轉換為浮點數)
G與 G 等價,但小數用 F,大數用 E浮點數、復數、整數(自動轉換為浮點數)
%百分比格式,數字自動乘上100后按 f 格式排版,並加 % 后綴浮點數、整數(自動轉換為浮點數)
常用的特殊格式類型:標准庫 datetime 給定的用於排版時間信息的格式類型,適用於 date、datetime 和 time 對象
格式描述符含義顯示樣例
%a星期幾(縮寫)'Sun'
%A星期幾(全名)'Sunday'
%w星期幾(數字,0 是周日,6 是周六)'0'
%u星期幾(數字,1 是周一,7 是周日)'7'
%d日(數字,以 0 補足兩位)'07'
%b月(縮寫)'Aug'
%B月(全名)'August'
%m月(數字,以 0 補足兩位)'08'
%y年(后兩位數字,以 0 補足兩位)'14'
%Y年(完整數字,不補零)'2014'
%H小時(24小時制,以 0 補足兩位)'23'
%I小時(12小時制,以 0 補足兩位)'11'
%p上午/下午'PM'
%M分鍾(以 0 補足兩位)'23'
%S秒鍾(以 0 補足兩位)'56'
%f微秒(以 0 補足六位)'553777'
%zUTC偏移量(格式是 ±HHMM[SS],未指定時區則返回空字符串)'+1030'
%Z時區名(未指定時區則返回空字符串)'EST'
%j一年中的第幾天(以 0 補足三位)'195'
%U一年中的第幾周(以全年首個周日后的星期為第0周,以 0 補足兩位)'27'
%w一年中的第幾周(以全年首個周一后的星期為第0周,以 0 補足兩位)'28'
%V一年中的第幾周(以全年首個包含1月4日的星期為第1周,以 0 補足兩位)'28'
綜合示例
>>> a = 1234
>>> f'a is {a:^#10X}' # 居中,寬度10位,十六進制整數(大寫字母),顯示0X前綴
'a is 0X4D2 '
>>> b = 1234.5678
>>> f'b is {b:<+10.2f}' # 左對齊,寬度10位,顯示正號(+),定點數格式,2位小數
'b is +1234.57 '
>>> c = 12345678
>>> f'c is {c:015,d}' # 高位補零,寬度15位,十進制整數,使用,作為千分分割位
'c is 000,012,345,678'
>>> d = 0.5 + 2.5j
>>> f'd is {d:30.3e}' # 寬度30位,科學計數法,3位小數
'd is 5.000e-01+2.500e+00j'
>>> import datetime
>>> e = datetime.datetime.today()
>>> f'the time is {e:%Y-%m-%d (%a) %H:%M:%S}' # datetime時間格式
'the time is 2018-07-14 (Sat) 20:46:02'
lambda表達式
f-string大括號內也可填入lambda表達式,但lambda表達式的 : 會被f-string誤認為是表達式與格式描述符之間的分隔符,為避免歧義,需要將lambda表達式置於括號 () 內:
>>> f'result is {lambda x: x ** 2 + 1 (2)}'
File "<fstring>", line 1
(lambda x)
^
SyntaxError: unexpected EOF while parsing
>>> f'result is {(lambda x: x ** 2 + 1) (2)}'
'result is 5'
>>> f'result is {(lambda x: x ** 2 + 1) (2):<+7.2f}'
'result is +5.00 '
————————————————
版權聲明:本文為CSDN博主「sunxb10」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/sunxb10/article/details/81036693
目錄
%用法
1、整數的輸出
%o —— oct 八進制
%d —— dec 十進制
%x —— hex 十六進制
1 >>> print('%o' % 20) 2 24 3 >>> print('%d' % 20) 4 20 5 >>> print('%x' % 20) 6 14
2、浮點數輸出
(1)格式化輸出
%f ——保留小數點后面六位有效數字
%.3f,保留3位小數位
%e ——保留小數點后面六位有效數字,指數形式輸出
%.3e,保留3位小數位,使用科學計數法
%g ——在保證六位有效數字的前提下,使用小數方式,否則使用科學計數法
%.3g,保留3位有效數字,使用小數或科學計數法
1 >>> print('%f' % 1.11) # 默認保留6位小數 2 1.110000 3 >>> print('%.1f' % 1.11) # 取1位小數 4 1.1 5 >>> print('%e' % 1.11) # 默認6位小數,用科學計數法 6 1.110000e+00 7 >>> print('%.3e' % 1.11) # 取3位小數,用科學計數法 8 1.110e+00 9 >>> print('%g' % 1111.1111) # 默認6位有效數字 10 1111.11 11 >>> print('%.7g' % 1111.1111) # 取7位有效數字 12 1111.111 13 >>> print('%.2g' % 1111.1111) # 取2位有效數字,自動轉換為科學計數法 14 1.1e+03
(2)內置round()
round(number[, ndigits])
參數:
number - 這是一個數字表達式。
ndigits - 表示從小數點到最后四舍五入的位數。默認值為0。
返回值
該方法返回x的小數點舍入為n位數后的值。
round()函數只有一個參數,不指定位數的時候,返回一個整數,而且是最靠近的整數,類似於四舍五入,當指定取舍的小數點位數的時候,一般情況也是使用四舍五入的規則,但是碰到.5的情況時,如果要取舍的位數前的小數是奇數,則直接舍棄,如果是偶數則向上取舍。
注:“.5”這個是一個“坑”,且python2和python3出來的接口有時候是不一樣的,盡量避免使用round()函數吧
1 >>> round(1.1125) # 四舍五入,不指定位數,取整 2 1 3 >>> round(1.1135,3) # 取3位小數,由於3為奇數,則向下“舍” 4 1.113 5 >>> round(1.1125,3) # 取3位小數,由於2為偶數,則向上“入” 6 1.113 7 >>> round(1.5) # 無法理解,查閱一些資料是說python會對數據進行截斷,沒有深究 8 2 9 >>> round(2.5) # 無法理解 10 2 11 >>> round(1.675,2) # 無法理解 12 1.68 13 >>> round(2.675,2) # 無法理解 14 2.67 15 >>>
3、字符串輸出
%s
%10s——右對齊,占位符10位
%-10s——左對齊,占位符10位
%.2s——截取2位字符串
%10.2s——10位占位符,截取兩位字符串
1 >>> print('%s' % 'hello world') # 字符串輸出 2 hello world 3 >>> print('%20s' % 'hello world') # 右對齊,取20位,不夠則補位 4 hello world 5 >>> print('%-20s' % 'hello world') # 左對齊,取20位,不夠則補位 6 hello world 7 >>> print('%.2s' % 'hello world') # 取2位 8 he 9 >>> print('%10.2s' % 'hello world') # 右對齊,取2位 10 he 11 >>> print('%-10.2s' % 'hello world') # 左對齊,取2位 12 he
4、 其他
(1)字符串格式代碼

(2)常用轉義字符

format用法
相對基本格式化輸出采用‘%’的方法,format()功能更強大,該函數把字符串當成一個模板,通過傳入的參數進行格式化,並且使用大括號‘{}’作為特殊字符代替‘%’
位置匹配
(1)不帶編號,即“{}”
(2)帶數字編號,可調換順序,即“{1}”、“{2}”
(3)帶關鍵字,即“{a}”、“{tom}”
1 >>> print('{} {}'.format('hello','world')) # 不帶字段 2 hello world 3 >>> print('{0} {1}'.format('hello','world')) # 帶數字編號 4 hello world 5 >>> print('{0} {1} {0}'.format('hello','world')) # 打亂順序 6 hello world hello 7 >>> print('{1} {1} {0}'.format('hello','world')) 8 world world hello 9 >>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 帶關鍵字 10 world hello world
>>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+版本支持 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # 可打亂順序 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # 可重復 'abracadabra'
>>> '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' >>> a = {'a': 'test_a', 'b': 'test_b'} >>> 'X: {0[a]}; Y: {0[b]}'.format(a) 'X: test_a; Y: test_b'
格式轉換
1 >>> print('{0:b}'.format(3)) 2 11 3 >>> print('{:c}'.format(20)) 4 5 >>> print('{:d}'.format(20)) 6 20 7 >>> print('{:o}'.format(20)) 8 24 9 >>> print('{:x}'.format(20)) 10 14 11 >>> print('{:e}'.format(20)) 12 2.000000e+01 13 >>> print('{:g}'.format(20.1)) 14 20.1 15 >>> print('{:f}'.format(20)) 16 20.000000 17 >>> print('{:n}'.format(20)) 18 20 19 >>> print('{:%}'.format(20)) 20 2000.000000% 21 >>>
進階用法
進制轉換
>>> # 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'
左中右對齊及位數補全
(1)< (默認)左對齊、> 右對齊、^ 中間對齊、= (只用於數字)在小數點后進行補齊
(2)取位數“{:4s}”、"{:.2f}"等
>>> print('{} and {}'.format('hello','world')) # 默認左對齊 hello and world >>> print('{:10s} and {:>10s}'.format('hello','world')) # 取10位左對齊,取10位右對齊 hello and world >>> print('{:^10s} and {:^10s}'.format('hello','world')) # 取10位中間對齊 hello and world >>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小數 1.123 is 1.12 >>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小數,右對齊,取10位 1.123 is 1.12 >>> '{:<30}'.format('left aligned') # 左對齊 'left aligned ' >>> '{:>30}'.format('right aligned') # 右對齊 ' right aligned' >>> '{:^30}'.format('centered') # 中間對齊 ' centered ' >>> '{:*^30}'.format('centered') # 使用“*”填充 '***********centered***********' >>>'{:0=30}'.format(11) # 還有“=”只能應用於數字,這種方法可用“>”代替 '000000000000000000000000000011'
正負符號顯示
>>> '{:+f}; {:+f}'.format(3.14, -3.14) # 總是顯示符號 '+3.140000; -3.140000' >>> '{: f}; {: f}'.format(3.14, -3.14) # 若是+數,則在前面留空格 ' 3.140000; -3.140000' >>> '{:-f}; {:-f}'.format(3.14, -3.14) # -數時顯示-,與'{:f}; {:f}'一致 '3.140000; -3.140000'
百分數%
>>> 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'
逗號","分隔金錢,沒以前進位
>>> '{:,}'.format(1234567890) '1,234,567,890'
占位符嵌套
>>> 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) # 官方文檔給出來的,無法在IDLE復現 3232235521 >>> >>> 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 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
占位符%s和%r
""" replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}" conversion ::= "r" | "s" | "a" 這里只有三個轉換符號,用"!"開頭。 "!r"對應 repr();"!s"對應 str(); "!a"對應ascii()。 """ >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2" # 輸出結果是一個帶引號,一個不帶
format的用法變形
# a.format(b) >>> "{0} {1}".format("hello","world") 'hello world' # f"xxxx"
# 可在字符串前加f以達到格式化的目的,在{}里加入對象,此為format的另一種形式:
>>> a = "hello" >>> b = "world" >>> f"{a} {b}" 'hello world' name = 'jack' age = 18 sex = 'man' job = "IT" salary = 9999.99 print(f'my name is {name.capitalize()}.') print(f'I am {age:*^10} years old.') print(f'I am a {sex}') print(f'My salary is {salary:10.3f}') # 結果 my name is Jack. I am ****18**** years old. I am a man My salary is 9999.990

