python f-string 备忘表

Python f-string 备忘单

ref https://fstring.help/cheat/

ref https://cheatography.com/brianallan/cheat-sheets/python-f-strings-basics/
ref https://cheatography.com/brianallan/cheat-sheets/python-f-strings-number-formatting/

数字

num format
%d 整数
%e 科学计数
%f 浮点
% 百分数
%b 二进制
%o 八进制
%x 十六进制
%c Unicode

integer = 123
number_ = 9876.6789
percent = 0.98765

var num format f-string output
integer 123 d f’{integer:d}’ 123
integer 123 b f’{integer:b}’ 1111011
integer 123 8b f’{integer:8b}’ 1111011
integer 123 _b f’{integer:_b}’ 111_1011
integer 123 09_b f’{integer:09_b}’ 0111_1011
integer 123 o f’{integer:o}’ 173
integer 123 #o f’{integer:#o}’ 0o173
integer 123 x f’{integer:x}’ 7b
integer 123 #x f’{integer:#x}’ 0x7b
integer 123 08x f’{integer:08x}’ 0000007b
integer 123 c f’{integer:c}’ {
number_ 9876.6789 f f’{number_:f}’ 9876.678900
number_ 9876.6789 .2f f’{number_:.2f}’ 9876.68
number_ 9876.6789 09.2f f’{number_:09.2f}’ 009876.68
number_ 9876.6789 09.5f f’{number_:09.5f}’ 9876.67890
number_ 9876.6789 .2f f’{number_:.2f}’ 9876.68
percent 0.98765 % f’{percent:%}’ 98.765000%
percent 0.98765 9.5% f’{percent:9.5%}’ 98.76500%
percent 0.98765 09.4% f’{percent:09.4%}’ 098.7650%
percent 0.98765 09.5% f’{percent:09.5%}’ 98.76500%
number_ 9876.6789 .2e f’{number_:.2e}’ 9.88e+03
number_ 9876.6789 09.2e f’{number_:09.2e}’ 09.88e+03

string = “Python”

var num format f-string output
string Python 20 f’{string:20}’ Python
string Python >20 f’{string:>20}’ Python
string Python <20 f’{string:<20}’ Python
string Python ^20 f’{string:^20}’ Python
string Python >>20 f’{string:>>20}’ >>>>>>>>>>>>>>Python
string Python <<20 f’{string:<<20}’ Python<<<<<<<<<<<<<<
string Python ^^20 f’{string:^^20}’ ^^^^^^^Python^^^^^^^
string Python =^20 f’{string:=^20}’ =======Python=======

Python f-string cheat sheet