ITPub博客

首页 > IT职业 > IT图书 > python使用f格式化字符串

python使用f格式化字符串

IT图书 作者:qj_zhai 时间:2021-09-11 09:56:23 0 删除 编辑

1、若要格式化字符串,可在字符串开始引号前添加f或F。

2、通过这种方式,我们可以直接中引入变量值,只需将变量放在{ 和 }之间。

>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'

将Python变量放入{}外,还可将函数放入{}:

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.

以上就是python使用f格式化字符串的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4380/viewspace-2830119/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-12

  • 博文量
    76
  • 访问量
    661