99%的Python用户都不知道的f-string隐秘技巧
f-string
想必很多Python
用户都基础性的使用过,作为Python
3.6版本开始引入的特性,通过它我们可以更加方便地向字符串中嵌入自定义内容,但f-string
真正蕴含的功能远比大多数用户知道的要丰富,今天我们就来一起get它们~
「最基础用法」
f-string
最基础的用法很简单,如下例所示,在前缀f
的字符串中向{}
内直接填入要嵌入的值、变量或计算表达式:

「自记录表达式」
从Python
3.8版本开始,为f-string
引入了「自记录表达式」,使得我们可以按照下面的写法快速输出一些计算表达式:

「多行f-string」
通过最外层包裹小括号,我们可以像下面这样非常灵活地撰写多行f-string
:

「在f-string中格式化日期」
针对日期类型的变量,我们可以参考下面的方式,直接在f-string
中快速地进行格式化:

「控制浮点数精度」
在f-string
中我们可以按照下列方式灵活地控制浮点数的小数位数:

「标准化显示宽度」
当我们需要对f-string
打印内容的显示最小宽度进行限制时,譬如打印出类似表格的结构,可以参考下面的例子:

「修改为左对齐」
f-string
默认为右对齐,就像上面的例子,但我们可以像下面这样使用<
修改显示模式为左对齐:

「设置科学计数法格式」
我们可以参考下面的方式实现指定位数的科学计数法显示方式:

「控制有效数字位数」
通过下面的方式,我们还可以控制所显示数字的有效数字位数,即从左开始第一个不为0的数字往右一共显示的个数,当位数低于整数部分时会自动变成科学计数法格式:

以上就是本文的全部内容,欢迎在评论区分享你的观点和意见~

加入知识星球【我们谈论数据科学】
300+小伙伴一起学习!
· 推荐阅读 ·
评论