Python的f-strings格式化

本文介绍Python 3.6引入的f-string格式化字符串的多种实用技巧,包括简化变量输出、格式化数字和日期、对齐字符串等,帮助开发者更高效地处理字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学过Python的朋友应该都知道 f-strings 是用来非常方便的格式化输出的,觉得它的使用方法无外乎就是print(f'value = { value }',其实,f-strings远超你的预期,今天来梳理一下它还能做那些很酷的事情。

常见用法

f-string,亦称为格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法,该方法源于PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加简便。f-string在形式上是以 f 或 F 修饰符引领的字符串(f'xxx'或 F'xxx'),以大括号 {} 标明被替换的字段;f-string在本质上并不是字符串常量,而是一个在运行时运算求值的表达式。

1、懒得再敲一遍变量名

str_value = "hello,python coders"   
print(f"{ str_value = }")    
# str_value = 'hello,python coders'

2、直接改变输出结果

num_value = 123    
print(f"{num_value % 2 = }")    
# num_value % 2 = 1

3、直接格式化日期

import datetime   
today = datetime.date.today()   
print(f"{today: %Y%m%d}")    
# 20211019    
print(f"{today =: %Y%m%d}")  
# today = 20211019

4、2/8/16 进制输出真的太简单

>>> a = 42    
>>> f"{a:b}" # 2进制    
'101010'    
>>> f"{a:o}" # 8进制    
'52'    
>>> f"{a:x}" # 16进制,小写字母    
'2a'    
>>> f"{a:X}" # 16进制,大写字母    
'2A'    
>>> f"{a:c}" # ascii 码    
'*'  

5、格式化浮点数

>>> num_value = 123.456    
>>> f'{num_value = :.2f}' #保留 2 位小数    
'num_value = 123.46'    
>>> nested_format = ".2f" #可以作为变量    
>>> print(f'{num_value:{nested_format}}')    
123.46

6、字符串对齐,so easy!

>>> x = 'test'    
>>> f'{x:>10}'   # 右对齐,左边补空格    
'      test'    
>>> f'{x:*<10}'  # 左对齐,右边补*    
'test******'    
>>> f'{x:=^10}'  # 居中,左右补=    
'===test==='    
>>> x, n = 'test', 10    
>>> f'{x:~^{n}}' # 可以传入变量 n    
'~~~test~~~'    
>>>

7、使用 !s,!r

>>> x = '中'    
>>> f"{x!s}" # 相当于 str(x) 
'中'    
>>> f"{x!r}" # 相当于 repr(x)    
"'中'"

8、自定义格式

class MyClass:    
    def __format__(self, format_spec) -> str:   
        print(f'MyClass __format__ called with {format_spec=!r}')  
        return "MyClass()"      
print(f'{MyClass():bala bala  %%MYFORMAT%%}')

输出如下:

MyClass __format__ called with format_spec='bala bala  %%MYFORMAT%%'    
MyClass() 

最后

Python 的 f-string 非常灵活优雅,同时还是效率最高的字符串拼接方式:

Python的f-strings格式化Python的f-strings格式化

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值