字符串格式化用來把整數、實數等對象轉化為特定格式的字符串
% 格式字符:% 之前的字符串為格式字符串,之後的部分為需要格式化的內容。
例如:
name = "cspsy"
job = "student"
print("My name is %s." % name)
# 如果有多個需要進行格式化的內容,需要使用 () 將其包裹。
print("My name is %s and my job is %s." % (name, job))


format(): .format() 之前的字符串為格式字符串,裡面的部分的內容為需要格式化的內容。
格式串中的 {} 的內容與 format() 裡面的內容相對應。
format() 方法進行格式化:
name = "cspsy"
job = "student"
print("My name is {} and my job is {}.".format(name, job))

one, two, three = 1, 2, 3
print("You use {0}, {2}, {1}.".format(one, two, three))

{} 內使用自定義的參數名字,與待格式化的內容對應。one, two, three = 1, 2, 3
print("You use {o}, {thr}, {tw}.".format(o=one, tw=two, thr=three))

將解包後的名字,key 值放在格式化字符串內。
例如:
number = {
'one': 1, 'two': 2, 'three': 3}
print("You use {one}, {three}, {two}.".format(**number))

進制轉換
one, two, three = 11111, 2222, 3
print("You use {0:#x}, {1:#o}, {2:#b}".format(one, two, three))

保留小數點
使用 :.xf,x 為想要保留的小數點個數,如果 : 後面帶有 +,則會保留符號輸出。
one, two, three = 11111.1111, 2.2222, 3.3333333
print("You use {0:.2f}, {1:+.0f}, {2:.3f}".format(one, two, three))

科學計數法
one, two, three = 11111.1111, 2.2222, 3.3333333
print("You use {0:.2e}, {1:+.0e}, {2:.3e}".format(one, two, three))

百分比形式
one, two, three = 11111.1111, 2.2222, 3.3333333
print("You use {0:.0%}, {1:.2%}, {2:.3%}".format(one, two, three))

以逗號分隔
one, two, three = 11111.1111, 2.2222, 3.3333333
print("You use {0:,}, {1:,}, {2:,}".format(one, two, three))

使用 :cxn 來進行,n 為最小長度,c 為長度不夠時,填充的字符(不寫則為空格)x 為對齊方式:其中,^:居中,<:左對齊,>:右對齊
例如:
one, two, three = 11111.1111, 2.2222, 3.3333333
print("You use {0:#^12.2f}, {1:.<+8.0f}, {2:>7.3f}".format(one, two, three))

可以通過內置 map() 函數來進行格式化字符串輸出:
formatter = "You use {0}".format
for num in map(formatter, range(1, 6)):
print(num)

這個例子寫法與下面等價:
formatter = "You use {0}".format
for num in range(1, 6):
print(formatter(num))
從 Python 3.6.x 開始支持一種新的字符串格式化方式,官方叫做 Formatted String Literals,簡稱 f-字符串,在字符串前加字母 f,在 {} 裡填寫表達式。
使用如下:
one, two, three = 11, 222, 3333
print(f'You use {
one}, {
two * three}.')

Python 3.8 之後,還可以 {xxx=},將 xxx=輸出出來且輸出它對應的值:
one, two, three = 1, 2, 3
print(f'You use {
one}, {
two * three}, {
two * three = }.')

Meituan of Python crawler series optimized automatic management of goods on the merchant side (product release, product scheduling, order collection)
Python Reptile series MeiTuan
2. The first step by step teach you how to use pycharm running Django project
The following steps show how t