In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
这篇文章主要讲解了"在Python中f-string的技巧有哪些",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"在Python中f-string的技巧有哪些"吧!
最基础用法
f-string最基础的用法很简单,如下例所示,在前缀f的字符串中向{}内直接填入要嵌入的值、变量或计算表达式:
print(f'1+1 = {2}')#输出:1+1 = 2a=1 + 1print(f'1+1 = {a}')#输出:1+1 = 2print(f'1+1 = {1+1}')#输出:1+1 = 2自记录表达式
从Python3.8版本开始,为f-string引入了自记录表达式,使得我们可以按照下面的写法快速输出一些计算表达式:
import matha = 8print(f'{math. log(8) = }')#输出:math. log(8) = 2.0794415416798357多行f-string
通过最外层包裹小括号,我们可以像下面这样非常灵活地撰写多行f-string:
a = 1b = 2c = 3s = ( f'{a = }\n' f'{b = }\n' f'{c = }\n')print(s)#输出:a = 1b = 2c = 3在f-string中格式化日期
针对日期类型的变量,我们可以参考下面的方式,直接在f-string中快速地进行格式化:
import datetimenow = datetime.datetime.now()print(f'{now:%Y年%m月%d号%H点%M分%S秒}')#输出:2021年10月18号16点45分58秒控制浮点数精度
在f-string中我们可以按照下列方式灵活地控制浮点数的小数位数:
import mathpi = math.piprint(f'{pi: .3f}')print(f'{pi:.8f}')#输出3.1423.14159265标准化显示宽度
当我们需要对f-string打印内容的显示最小宽度进行限制时,譬如打印出类似表格的结构,可以参考下面的例子:
for x in range(1,11): print(f'{x:02}|{x**2:3}/{x**5:6}')#输出01| 1/ 102| 4/ 3203| 9/ 24304| 16/ 102405| 25/ 312506| 36/ 777607| 49/ 1680708| 64/ 3276809| 81/ 5904910|100/100000修改为左对齐
f-string默认为右对齐,就像上面的例子,但我们可以像下面这样使用
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.