日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

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

作者:寧萌Julie ? 更新時間: 2023-06-19 編程語言

最近看深度學習的代碼時發(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'))

顯示結(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ù)點后有幾位。例如:

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() 中可以傳入變量運算的值,比如例子中的 price*number。

5.{} 中可以加上數(shù)字索引,對應的是 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} 對應 format(6,3) 的第一個值 6,{1} 對應第二個值 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

原文鏈接:https://blog.csdn.net/applebear1123/article/details/124795504

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新