欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中str.format()和f-string的使用

 更新時間:2023年02月27日 09:31:10   作者:寧萌Julie  
本文主要介紹了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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論