f-string,亦称为格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法,该方法源于PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加简便。f-string在形式上是以 f 或 F 修饰符引领的字符串(f'xxx'或 F'xxx'),以大括号 {} 标明被替换的字段;f-string在本质上并不是字符串常量,而是一个在运行时运算求值的表达式
自定义格式:对齐、宽度、符号、补零、精度、进制等
f-string采用 {content:format} 设置字符串格式,其中 content 是替换并填入字符串的内容,可以是变量、表达式或函数等,format是格式描述符。采用默认格式时不必指定 {:format},如上面例子所示只写 {content} 即可。
>>> a = 123.456 >>> f'a is {a:8.2f}' 'a is 123.46' >>> f'a is {a:08.2f}' 'a is 00123.46' >>> f'a is {a:8.2e}' 'a is 1.23e+02' >>> f'a is {a:8.2%}' 'a is 12345.60%' >>> f'a is {a:8.2g}' 'a is 1.2e+02' >>> s = 'hello' >>> f's is {s:8s}' 's is hello ' >>> f's is {s:8.3s}' 's is hel '
链接:https://blog.csdn.net/whatday/article/details/106729795