f-string 高效的字符串格式化

f-string,称为格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法,该方法源于PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加简便。

python中常用有3种字符串格式化的方法:

  • 占位符 例如 print("my name is " % "hanmeimei")
  • format 例如 print("my name is {}".format("hanmeimei"))
  • f-string 例如 print(f"my name is {'hanmeimei'}")

其中f-string是推荐的最清晰,效率最高的方法。本篇主要讲解f-string常见的使用方法。

1|0语法


f-string采用content:format} 设置字符串格式,其中 content 是替换并填入字符串的内容,可以是变量、表达式、函数等,format 是格式描述符,可以省略。

Python f-string 格式化字符串的完整格式说明是通过冒号(:)后面的格式规范符来实现的。这个格式化规范符可以用来控制数字、字符串、时间日期等数据类型的输出格式。以下是完整的格式说明,包括常见的格式化选项及其用法。

   
f "{expression:{flags}{width}{precision}{type}}"
  • expression: 要格式化的值(例如数字、字符串等)。
  • flags: 用于指定填充方式、对齐方式等。
  • width: 输出的最小宽度。如果输出的值宽度小于指定的宽度,则会进行填充。
  • precision: 用于控制浮动点数的小数点精度或其他数值精度。
  • type: 用于指定格式类型,例如浮动点数、整数、字符串等。

简单使用

f-string用大括号 {} 表示被替换字段,其中直接填入替换内容:

   
>>> name = 'Eric' >>> f 'Hello, my name is {name}' 'Hello, my name is Eric' >>> number = 7 >>> f 'My lucky number is {number}' 'My lucky number is 7' >>> price = 19.99 >>> f 'The price of this book is {price}' 'The price of this book is 19.99'

注意:不管变量的类型是什么,最后都会得到字符串类型的结果

2|0使用方法


2|1宽度控制


使用f-string最常见的就是控制变量精度和输出宽度

格式描述符含义与作用
width整数 width 指定宽度0width:整数 width 指定宽度,开头的 0 指定高位用 0 补足宽度
width.precision整数 width 指定宽度,整数 precision 指定显示精度

以圆点为分割,圆点之前控制输出宽度,原点之后控制输出精度。

控制输出宽度,不管是数值类型和字符串类型都可以。语法:f"{变量: 宽度}"

  • 指定宽度小于变量宽度:正常输出
  • 指定宽度大于变量宽度:输出指定宽度,以空格补齐。字符串右补齐,数值左补齐
   
>>> a = 3.1415926 # 变量宽度9,指定宽度20,数值左补齐 >>> print ( f "{a:20}" ) 3.1415926 >>> print ( len ( f "{a:20}" )) 20 >>> c = "hello world" >>> print ( f "{c:5}" ) hello world >>> print ( f "{c:25}" ) hello world # 变量只有11个字符串,指定宽度为25,输出长度为25,以空格补齐 >>> print ( len ( f "{c:25}" )) 25

有一个特别使用f"{变量: 0宽度}",在宽度前面加0可以实现变量显示前面用0补齐

   
>>> a = 3.1415926 >>> print ( f "{a:020}" ) 000000000003.1415926 >>>

2|2精度控制


数值

整型和浮点数使用f-string可以控制输出的精度。语法是 f"{变量: .4f}",其中4f是指小数点后的位数,可以实现精度截断或扩充。其中截断的规则是四舍五入,扩充是将精度增加到指定位数

   
>>> a = 3.1415926 >>> print ( f "{a:.4f}" ) 3.1416 >>> b = 100 >>> print ( f "{b}" ) '100' >>> print ( f "{b:.6f}" ) '100.000000' >>>

字符串

字符串同样可以控制输出精度,使用语法** f"{变量:.4s}"**, 其中4s指字符串的长度,s可以省略,可以实现截断,但不会填充。设置的长度大于变量长度,输出仍然是变量的长度。

   
>>> c = "hello world" >>> print ( f "{c:.2}" ) he >>> print ( f "{c:.10s}" ) hello worl >>> print ( f "{c:.5s}" ) hello # 精度超出长度不会填充 >>> print ( f "{c:.20s}" ) hello world >>> print ( len ( f "{c:.20s}" )) 11

可以同时控制宽度和精度

   
>>> a = 3.1415926 >>> print ( f "{a:14.4f}" ) 3.1416 >>> c = "hello world" >>> print ( f "{c:25.4s}" ) hell

2|3对齐


对齐是指输出时当指定宽度大于变量宽度时如何显示,可以选择的包括:

  • >: 右对齐
  • <: 左对齐 (默认行为)
  • ^: 居中对齐
   
>>> c = "hello world" # 设置宽度之后就会出现空格填充,字符串默认右填充即左对齐 >>> print ( f "{c:20}" ) hello world >>> print ( len ( f "{c:20}" )) 20 >>> print ( f "{c:<20}" ) hello world >>> >>> print ( f "{c:>20}" ) hello world >>> print ( f "{c:^20}" ) hello world

2|4填充


在对齐时默认使用空格填充,也可以使用指定字符填充。使用语法 **f"{变量: 填充字符<宽度}" **,填充字符常见:-、+、*、0等等

   
>>> c = "hello world" >>> print ( f "{c:<20}" ) hello world >>> print ( f "{c:-<20}" ) hello world --------- >>> print ( f "{c:->20}" ) --------- hello world >>> >>> print ( f "{c:-^20}" ) ---- hello world ----- >>> print ( f "{c:*^20}" ) **** hello world ***** >>> print ( f "{c:0^20}" ) 0000hello world00000

2|5数据格式


类型标识符 (type) 类型标识符决定了如何表示和格式化数值、字符串等常见数据类型。常见的类型标识符包括:

  • s: 字符串。
  • b: 二进制整数格式
  • d: 十进制整数(整数)
  • o: 八进制整数格式
  • x: 十六进制小写。
  • X: 十六进制大写。
  • c: 字符格式,按unicode编码将整数转换为对应字符
  • f: 浮动点数(默认的浮动点数)。
  • e: 科学计数法表示浮动点数。
  • g: 科学计数法或浮动点数(根据精度选择合适格式)。
  • %: 百分比格式,将浮动点数乘以 100 并附加 % 符号。

数值转十进制

   
>>> value = 0xff >>> value 255 >>> print ( f "{value:d}" ) 255

进制转换

   
>>> a = 378297640000 >>> # 10转2 >>> print ( f "{a:b}" ) 101100000010100010010111110010001000000 # 10转8 >>> print ( f "{a:d}" ) 378297640000 # 10转16 >>> print ( f "{a:x}" ) 58144be440

默认不添加进制的前缀,使用# 可以添加

   
>>> a = 378297640000 >>> print ( f "{a:#b}" ) 0b101100000010100010010111110010001000000 >>> print ( f "{a:#d}" ) 378297640000 >>> print ( f "{a:#x}" ) 0x58144be440 >>> print ( f "{a:#X}" ) 0X58144BE440

变量转浮点数

   
>>> value = 0xff >>> print ( f "{value:f}" ) 255.000000 >>>

将整数转换为unicode编码对应字符

   
>>> a = 69 >>> print ( f "{a:c}" ) E >>> a = 290 >>> print ( f "{a:c}" ) Ģ >>> a = 2736 >>> print ( f "{a:c}" )

科学计数法

   
>>> a = 378297640000 >>> >>> print ( f "{a:e}" ) 3.782976e+11 >>> b = - 0.132465 >>> >>> print ( f "{b:e}" ) - 1.324650e-01

百分号

将浮动点数乘以 100 并附加 % 符号

   
>>> a = 0.5473 >>> print ( f "{a:%}" ) 54.730000 %

2|6时间格式


fstring 以通过结合 datetime 模块来实现时间的格式化。更多格式可自行查阅。

   
>>> from datetime import datetime >>> >>> now = datetime . now () >>> >>> now datetime . datetime ( 2025 , 5 , 15 , 17 , 42 , 6 , 490934 ) >>> formatted_time = f "{now:%Y-%m-%d %H:%M:%S}" >>> print ( formatted_time ) 2025 - 05 - 15 17 : 42 : 06 >>>

3|0综合使用


浮点数填充到20位中间对齐保留2位小数点

   
>>> a = 3.1415926 >>> print ( f "{a:-^20.2f}" ) -------- 3.14 --------

整数填充到30位右对齐转换成十六进制

   
>>> a = 378297640000 >>> print ( f "{a:+>30x}" ) ++++++++++++++++++++ 58144be440

参考:

https://www.wangxhub.com/2024/12/08/python-f-string-format/

https://blog.youkuaiyun.com/sunxb10/article/details/81036693


__EOF__

本文作者goldsunshine
本文链接https://www.cnblogs.com/goldsunshine/p/18889537.html
关于博主:评论和私信会在第一时间回复。或者 直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角 推荐一下。您的鼓励是博主的最大动力!
原创作者: goldsunshine 转载于: https://www.cnblogs.com/goldsunshine/p/18889537
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值