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

最近看深度学习的代码时发现,显示训练过程的 loss 时,经常会用到 print(''.format())print(f'') ,学习了一下用法,在这里分享,欢迎交流和指教!

string format 有两种方式:

方式一 (str.format()) :print('{}'.format(var))

1.{} 是占位符 ( placeholder ),对应的值在 format() 的括号内。

例如:

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.{} 可以设置变量格式,前面要加上 :,其后的数字表示这个整数、或字符串、或小数点后有几位。例如:

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.{} 中可以加上数字索引,对应的是 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

本文对您有帮助的话,请点赞支持一下吧,谢谢!

关注我 宁萌Julie,多多交流,一起学习提高吧!

参考:https://www.freecodecamp.org/news/python-string-format-python-s-print-format-example/

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值