Python中str.format()和f-string的使用
最近看深度學(xué)習(xí)的代碼時發(fā)現(xiàn),顯示訓(xùn)練過程的 loss 時,經(jīng)常會用到 print(''.format()) 或 print(f'') ,學(xué)習(xí)了一下用法,在這里分享,歡迎交流和指教!
string format 有兩種方式:
方式一 (str.format()) :print('{}'.format(var))
1.{} 是占位符 ( placeholder ),對應(yīng)的值在 format() 的括號內(nèi)。
例如:
print('Hi, {}!'.format('Mary'))
顯示結(jié)果為:
Hi, Mary!
2.format() 中可以填入變量,這種方式更常見。例如:
name='Julie'
print('Hi, {}!'.format(name))
顯示結(jié)果為:
Hi, Julie!
3.還可以有多個變量。例如:
num_apple=6
num_orange=3
print('I bought {} apples and {} oranges.'.format(num_apple,num_orange))顯示結(jié)果為:
I bought 6 apples and 3 oranges.
4.{} 可以設(shè)置變量格式,前面要加上 :,其后的數(shù)字表示這個整數(shù)、或字符串、或小數(shù)點(diǎn)后有幾位。例如:
fruit='apples'
number=6
price=1.2
print('{:5d} {:8}, price:{:.5f}.'.format(number,fruit,price*number))
顯示結(jié)果為:
6 apples , price:7.20000.
從結(jié)果可以看到:
(1) 比如 apples 有 6 位,設(shè)置格式為 8 位 {:8},結(jié)果顯示中 apples 后面有 2 位空格。
(2) format() 中可以傳入變量運(yùn)算的值,比如例子中的 price*number。
5.{} 中可以加上數(shù)字索引,對應(yīng)的是 format() 中的元素位置。例如:
print('I bought {1} oranges,{0} bananas and {0} apples.'.format(6,3))
顯示結(jié)果為:
I bought 3 oranges,6 bananas and 6 apples.
上面的語句中,{0} 對應(yīng) format(6,3) 的第一個值 6,{1} 對應(yīng)第二個值 3。
方式二 (f-string) :print(f'{var}')
注:這里既可以用 f'',也可以用 F''。
1.與方式一不同,f'{}'直接在{}寫入變量值。例如:
name='Julie'
print(f'{name} is learning Python.')
顯示結(jié)果為:
Julie is learning Python.
2.與方式一相同,f'' 也可以設(shè)置多個變量。例如:
num_apple=6
num_orange=3
print(f'I bought {num_apple} apples and {num_orange} oranges.')
顯示結(jié)果為:
I bought 6 apples and 3 oranges.
3.與方式一相同,{} 中可以設(shè)置格式。例如:
fruit='apples'
number=6
price=1.2
print(f'{number:5d} {fruit:8}, price:{price*number:.5f}')
顯示結(jié)果為:
6 apples , price:7.20000
到此這篇關(guān)于Python中str.format()和f-string的使用的文章就介紹到這了,更多相關(guān)Python str.format()和f-string內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pandas實(shí)現(xiàn)按照Series分組示例
本文主要介紹了pandas按照Series分組示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
python GUI庫圖形界面開發(fā)之PyQt5單行文本框控件QLineEdit詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5單行文本框控件QLineEdit詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-02-02
pycharm遠(yuǎn)程調(diào)試openstack代碼
這篇文章主要為大家詳細(xì)介紹了pycharm遠(yuǎn)程調(diào)試openstack的代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
sublime python3 輸入換行不結(jié)束的方法
下面小編就為大家分享一篇sublime python3 輸入換行不結(jié)束的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04

