為什么要做網(wǎng)站首頁設(shè)計汕頭seo優(yōu)化項目
文章目錄
- 一、format語法
- 二、format格式化的用法
- 2.1、按照先后順序替換{}
- 2.2、按照索引進行匹配替換{0}
- 2.3、按關(guān)鍵字索引進行匹配替換
- 2.4、通過列表索引格式化字符串
- 2.5、使用元組
- 2.6、通過字典設(shè)置格式化字符串
- 2.7、混合使用
- 三、字符串填充與對齊
- 3.1、左對齊及填充
- 3.2、右對齊及填充
- 3.3、居中對齊及填充
- 四、格式化
- 4.1、格式化數(shù)字
- 4.2、格式化日期和時間
- 五、format() 方法綜合應用
format函數(shù)是Python中強大的字符串格式化方法,它允許程序員通過大括號{}來為字符串中的插入點占位,并通過傳入?yún)?shù)進行替換,{0}、{1}分別代表不同的參數(shù)
以下內(nèi)容基于Python3.13進行講解。
一、format語法
官網(wǎng)地址:https://docs.python.org/zh-cn/3/library/functions.html#format
語法一:format()函數(shù)
format(value, format_spec='')
將 value 轉(zhuǎn)換為“格式化后”的形式,格式由 format_spec 進行控制。format_spec 的解釋方式取決于 value 參數(shù)的類型;
語法二:str.format()
str.format(*args, **kwargs) 常見形式為: ''.format()如:print('我是{}'.format('小明'))
{}
一般被稱為槽
format_spec常用格式:
'{[index][:[fill]align][sign][#][width][grouping_option][.precision][type]}{......}{......}'.format(),格式中[]內(nèi)的參數(shù)都是可選參數(shù),每個{}都表示是一個待替換的字符串。format_spec ::= [[fill]align][sign]["z"]["#"]["0"][width][grouping_option]["." precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= digit+
grouping_option ::= "_" | ","
precision ::= digit+
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
index:指定冒號后面出現(xiàn)的參數(shù)在format()中的索引值,如果沒有,則以format()中的默認順序自動分配。
fill:指定空白處的填充符,默認是空格,可以是任意單個字符
。
align:指定數(shù)字的對齊方式。
align | 含義 |
---|---|
< | 左對齊,對于大部分對象時為默認 |
> | 右對齊,對于數(shù)字時為默認 |
= | 數(shù)據(jù)右對齊,同時將符號放置在填充內(nèi)容的最左側(cè),該選項只對數(shù)字類型有效 |
^ | 數(shù)據(jù)居中,此選項需和 width 參數(shù)一起使用 |
請注意,除非定義了最小字段寬度,否則字段寬度將始終與填充它的數(shù)據(jù)大小相同,因此在這種情況下,對齊選項沒有意義。
sign:指定有無符號數(shù) 。
sign | 含義 |
---|---|
+ | 正數(shù)前面添加 ‘ + ’ ,負數(shù)前面加 ‘ - ’ 例如 +3 , -1 。 |
- | 表示正負號僅用于負數(shù)(這是默認行為 )。正數(shù)前面不添加 ‘ + ’ ,負數(shù)前面加 ‘ - ’。例如 3 , -1。 |
space | 正數(shù)前面添加 ‘ 空格 ’ ,負數(shù)前面加 ‘ - ’ |
# | 對于二進制數(shù)、八進制數(shù)和十六進制數(shù),使用此參數(shù),各進制數(shù)前會分別顯示 0b、0o、0x前綴;反之則不顯示前綴 |
width:指定輸出數(shù)據(jù)時所占的寬度。
grouping_option :千分位分隔符,一般為"_" 或 “,” 。
.precision:如果后面存在type參數(shù),則指的是保留小數(shù)的位數(shù),如果type參數(shù)不存在,則是指有效數(shù)字的位數(shù)。
type:指定輸出數(shù)據(jù)的具體類型。
type | 含義 |
---|---|
s | 對字符串類型格式化,這是字符串的默認類型,可以省略。 |
% | 顯示百分比,默認顯示小數(shù)點后六位,將數(shù)字乘以 100 后面帶一個百分號。 |
d | 十進制整數(shù) |
c | 將十進制整數(shù)自動轉(zhuǎn)化成對應的Unicode字符 |
b | 將十進制數(shù)自動轉(zhuǎn)化成二進制數(shù),并格式化輸出 |
o | 將十進制數(shù)自動轉(zhuǎn)化成八進制數(shù),并格式化輸出 |
x | 十六進制數(shù),a 到 f 小寫 |
X | 十六進制數(shù),A 到 F 大寫。 在指定 ‘#’ 的情況下,前綴 ‘0x’ 也將被轉(zhuǎn)為大寫形式 ‘0X’。 |
e | 轉(zhuǎn)化成科學計數(shù)法,并格式化輸出 |
E | 科學計數(shù)法。 與 ‘e’ 相似,不同之處在于它使用大寫字母 ‘E’ 作為分隔字符。 |
f | 轉(zhuǎn)化為浮點數(shù),對 float 采用小數(shù)點之后 6 位精度,而對 Decimal 則使用大到足夠顯示所有系數(shù)位的精度。 |
F | 定點表示。 與 ‘f’ 相似,但會將 nan 轉(zhuǎn)為 NAN 并將 inf 轉(zhuǎn)為 INF。 |
g、G | 自適應轉(zhuǎn)化為e或f(E或F),并格式化輸出 |
簡單示例:
print("{0}{1}".format("Hello"," World!")) #輸出:Hello World!
print("{0:+<20}".format("Python"))#輸出:Python++++++++++++++
print("{0:+>20}".format("Python"))#輸出:++++++++++++++Python
print("{0:+^20}".format("Python"))#輸出:+++++++Python+++++++
#還可以不需要槽樣式,直接將槽樣式寫在format函數(shù)的參數(shù)里
print(format("Hello"),format("World")) #輸出:Hello World!
print(format("Python",'+<20'))#輸出:Python++++++++++++++
print(format("Python",'+>20'))#輸出:++++++++++++++Python
print(format("Python",'+^20'))#輸出:+++++++Python+++++++
二、format格式化的用法
2.1、按照先后順序替換{}
格式如下:
"{} {}".format(values1, values2)
說明:format 會把參數(shù)按位置順序來填充到字符串中,按照順序自動分配,而且一個參數(shù)可以多次插入。{{}} 僅代表{},不占用字符串格式化位置順序。
示例:
# {} 和參數(shù)的個數(shù)必須匹配,否則會報錯。
name='張三'
age=19
s="我的名字是:{},年齡是:{}"
print(s.format(name,age) )
輸出為:
我的名字是:張三,年齡是:19
2.2、按照索引進行匹配替換{0}
格式如下:
"{0} {1}".format(value1, value2)
說明:按索引編號來匹配替換 {索引} 的值。
{0},{1}代表的占位符,數(shù)字占位符要注意順序。下標從0開始
。
name='張三'
age=19
s="我的名字是:{0},年齡是:{1}"
print(s.format(name,age) )
輸出為:
我的名字是:張三,年齡是:19
索引下標可多次使用
print('我是{0},我喜歡{1},你喜歡{1}嗎?'.format('小明','打羽毛球'))輸出:我是小明,我喜歡打羽毛球,你喜歡打羽毛球嗎?
先后順序與索引下標不能混合一起使用,下面的用法將報錯:
print('我是{0},我喜歡{1},你喜歡{}嗎?'.format('小明','打羽毛球','乒乓球'))輸出:
ValueError: cannot switch from manual field specification to automatic field numbering
索引下標不能越界,即不能超過format給出的值數(shù)量,注意下標是0開始,下面用法將報錯:
print('我是{2}'.format('小明','打羽毛球'))輸出:IndexError: tuple index out of range
2.3、按關(guān)鍵字索引進行匹配替換
格式如下:
"{關(guān)鍵字索引1} {關(guān)鍵字索引2}".format(關(guān)鍵字索引1 = value1, 關(guān)鍵字索引2 = value2)
s="我的名字是:{name},年齡是:{age}"
print(s.format(age=19,name='張三') )year = 2024
month = 11
s = "現(xiàn)在是{year1}年{month1}月"
print(s.format(year1=year,month1=month) )
輸出為:
我的名字是:張三,年齡是:19
現(xiàn)在是2024年11月
2.4、通過列表索引格式化字符串
格式如下:
列表名=['列表值1','列表值2','列表值3'...]
"{List[列表索引1]},{List[列表索引2]}".format(List = 列表名)說明:在format格式化時,可使用 * 對list拆分
示例:
list1 = ["張三",22]
list2 = [2002,10,22]
list3 = ["Tom","Jerry","Rose","Black"]
list4 = [25,22,20,24]
print("我叫{list[0]},今年{list[1]}歲了。".format(list=list1))
print("我叫{0[0]},今年{0[1]}歲了。".format(list1))
print("李明的生日:{list[0]}-{list[1]}-{list[2]}".format(list=list2))
print("{0[0]}的年齡為{1[1]};{0[1]}的年齡為{1[2]};{0[2]}的年齡為{1[0]};{0[3]}的年齡為{1[3]}。".format(list3,list4))# 使用 *與** 對list進行拆分
print("李明的生日:{1}-{2}-{0}".format(*list2))運行結(jié)果為:
======================================================================
我叫張三,今年22歲了。
我叫張三,今年22歲了。
李明的生日:2002-10-22
Tom的年齡為22;Jerry的年齡為20;Rose的年齡為25;Black的年齡為24。
李明的生日:10-22-2002
關(guān)于*list
拆分列表的用法參考python中的*與**用法詳解
2.5、使用元組
元組與list用法一致,參考上面寫法。
test = ('小明','珠海市','天蝎座','小哥哥')
print('我是{0[0]},來自{0[1]}的{0[2]}一枚{0[3]}'.format(test))
print('我是{0},來自{1}的{2}一枚{3}'.format(*test))
print('我是{},來自{}的{}一枚{}'.format(*test))#輸出
D:\App\python\python3.13.0\python.exe D:\WorkSpace-Python\Test\test3.py
我是小明,來自珠海市的天蝎座一枚小哥哥
我是小明,來自珠海市的天蝎座一枚小哥哥
我是小明,來自珠海市的天蝎座一枚小哥哥
2.6、通過字典設(shè)置格式化字符串
格式如下:
字典名1={'字典索引1':'字典索引1的值', '字典索引2':'字典索引2的值', ...}
"{字典索引},{字典索引值}".format(字典名1) 說明:在format格式化時,可使用 ** 對字典拆分
dict1 = {"name":"張三","age":21}
dict2 = {"year":2002,"month":10,"day":22}
print("我叫{0[name]},今年{0[age]}歲了。".format(dict1))
print("我叫{0},今年{1}歲了。".format(*dict1))
print("李明的生日:{0[year]}-{0[month]}-{0[day]}".format(dict2))
print("李明的生日:{0[month]}-{0[day]}-{0[year]}".format(dict2))
print("我叫{name},今年{age}歲了".format(**dict1))
# python2.7中不支持多個**入?yún)?#xff0c;python3支持
print("我叫{name},今年{age}歲了。生日:{year}-{month}-{day}".format(**dict1,**dict2))運行結(jié)果為:
==========================================
我叫張三,今年21歲了。
我叫age,今年name歲了。
李明的生日:2002-10-22
李明的生日:10-22-2002
我叫張三,今年21歲了
我叫張三,今年21歲了。生日:2002-10-22
關(guān)于**dict
的用法參考python中的*與**用法詳解
2.7、混合使用
(1)可以通過索引,參數(shù)名來混合匹配。
(2)注意:命名參數(shù)必須放在最后。否則編譯時出現(xiàn)報錯!
(3)索引和默認格式化不可以混合使用。
(4)支持對參數(shù)部分引用,可以通過索引對參數(shù)的部分進行取值。
示例:
list1 = ["張三",21]
dict1 = {"year":2002,"month":10,"day":22}
print("我叫{},生日為:{year}-{month}-{day},今年{}歲了。".format(*list1,**dict1))
print("我叫{},今年{age}歲了。".format("李四",age=25))
# print("我叫{},今年{age}歲了。".format(age=25,"李四")) #此代碼錯誤,命名參數(shù)必須放在最后
print("我叫{},今年{1}歲了。".format("李四",25)) #此代碼錯誤,索引和默認格式化不可以混合使用程序運行結(jié)果為:
=====================D:\App\python\python3.13.0\python.exe D:\WorkSpace-Python\Test\test.py =====================
我叫張三,生日為:2002-10-22,今年21歲了。
我叫李四,今年25歲了。
Traceback (most recent call last):File "D:\WorkSpace-Python\Test\test.py", line 6, in <module>print("我叫{},今年{1}歲了。".format("李四",25))
ValueError: cannot switch from automatic field numbering to manual field specification
三、字符串填充與對齊
format支持左對齊
、右對齊
、居中對齊
。
如果你希望將變量打印在特定位置,可以使用對齊方式
更多對齊與填充的方法參考《Python字符串對齊的幾種方法、Python填充與對齊、Python中英文對齊》
3.1、左對齊及填充
格式如下:
:< # 左對齊填充
< # 左對齊,后面帶寬度
: # 后面帶填充的字符,只能是一個字符,不指定則默認是用空格填充
示例:
print('{:<10}!'.format('Python')) # 默認填充空格
print('{:0<10}!'.format('Python')) # 用0填充
print('{:<10}!'.format('中華人民萬歲')) # 默認填充空格運行結(jié)果:
======================================
D:\App\python\python3.13.0\python.exe D:\WorkSpace-Python\Test\test.py
Python !
Python0000!
中華人民萬歲 !
注意:python2與python3中對于中文字符串的填充是不一致的。
#python2
print('{:<10}!'.format('hello')) # 右邊補充5個空格,使長度為10
print('{:<10}!'.format('全世界')) # 右邊補充一個空格,因為len('全世界')發(fā)現(xiàn)長度為9
hello !
全世界 !# python3
print('{:<10}!'.format('hello')) # 右邊補充5個空格,使長度為10
print('{:<10}!'.format('全世界')) # 右邊補充7個空格,使長度為10
hello !
全世界 !
?在Python 2和Python 3中,len()函數(shù)的主要區(qū)別在于它們對字符串的處理方式不同。?
- 在?Python 2?中,len()函數(shù)返回的是
字節(jié)長度
。這意味著如果字符串中包含非ASCII字符(如中文、日文等),len()返回的將是字節(jié)數(shù)而不是字符數(shù)。例如,對于包含中文的字符串,len()返回的將是字節(jié)長度,而不是字符數(shù)?。- 而在?Python 3?中,len()函數(shù)直接返回
字符數(shù)量
。這是因為Python 3默認使用UTF-8編碼,而UTF-8編碼支持多字節(jié)字符,因此len()函數(shù)返回的是字符數(shù)而不是字節(jié)數(shù)。這意味著在處理包含非ASCII字符的字符串時,Python 3的len()函數(shù)能夠正確地返回字符數(shù)?
3.2、右對齊及填充
格式如下:
:> # 右對齊
> # 右對齊,后面帶寬度,
: # 后面帶填充的字符,只能是一個字符,不指定則默認是用空格填充
示例如下:
print('{:>10}!'.format('Python')) # 默認填充空格
print('{:0>10}!'.format('Python')) # 用0填充
print('{:>10}!'.format('中華人民萬歲')) # 默認填充空格運行結(jié)果:
======================================
D:\App\python\python3.13.0\python.exe D:\WorkSpace-Python\Test\test.py Python!
0000Python!中華人民萬歲!
3.3、居中對齊及填充
格式如下:
:^ # 居中對齊
^ # 居中對齊,后面帶寬度
: # 后面帶填充的字符,只能是一個字符,不指定則默認是用空格填充
示例如下:
print('{:^10}!'.format('Python')) # 默認填充空格
print('{:0^10}!'.format('Python')) # 用0填充
print('{:^10}!'.format('中華人民萬歲')) # 默認填充空格運行結(jié)果:
======================================
D:\App\python\python3.13.0\python.exe D:\WorkSpace-Python\Test\test.py Python !
00Python00!中華人民萬歲 !
四、格式化
4.1、格式化數(shù)字
更多詳細內(nèi)容參考另一篇文章:python format格式化數(shù)字
可以實現(xiàn)百分比、千分位、進制轉(zhuǎn)換、字符填充與對齊等等。
4.2、格式化日期和時間
format() 函數(shù)在處理日期和時間時也非常有用,可以將日期和時間對象格式化為特定的字符串表示。
from datetime import datetime# 格式化當前日期和時間
now = datetime.now()
formatted_datetime = "{:%Y-%m-%d %H:%M:%S}".format(now)
print("Formatted datetime:", formatted_datetime)
日期和時間符號參考:python中時間日期格式化符號
五、format() 方法綜合應用
(1)打印左對齊圖案
代碼如下:
for i in range(1, 11):print("{:<{}}".format("*" * i, 10))程序運行結(jié)果為:
D:\App\python\python3.13.0\python.exe D:\WorkSpace-Python\Test\test3.py
*
**
***
****
*****
******
*******
********
*********
**********
(2)打印右對齊圖案
代碼如下:
for i in range(1, 11):print("{:>{}}".format("*" * i, 10))程序運行結(jié)果為:
D:\App\python\python3.13.0\python.exe D:\WorkSpace-Python\Test\test3.py*********************************************
**********
(3)打印居中對齊圖案
代碼如下:
for i in range(1, 21, 2):print("{:^{}}".format("*" * i, 20))程序運行結(jié)果為:
D:\App\python\python3.13.0\python.exe D:\WorkSpace-Python\Test\test3.py* *** ***** ******* ********* *********** ************* *************** *****************
*******************
參考或推薦文章:
https://blog.csdn.net/weixin_44377973/article/details/132300478
數(shù)字格式化:python format格式化數(shù)字
https://zhuanlan.zhihu.com/p/632687543