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