Python 的 f-strings 作用远超你的预期

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

[[439592]]

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

1、懒得再敲一遍变量名 

  1. str_value = "hello,python coders"   
  2. print(f"{ str_value = }")    
  3. str_value = 'hello,python coders'  

2、直接改变输出结果 

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

3、直接格式化日期 

  1. import datetime   
  2. today = datetime.date.today()   
  3. print(f"{today: %Y%m%d}")    
  4. # 20211019    
  5. print(f"{today =: %Y%m%d}")  
  6. today = 20211019   

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

  1. >>> a = 42    
  2. >>> f"{a:b}" # 2进制    
  3. '101010'    
  4. >>> f"{a:o}" # 8进制    
  5. '52'    
  6. >>> f"{a:x}" # 16进制,小写字母    
  7. '2a'    
  8. >>> f"{a:X}" # 16进制,大写字母    
  9. '2A'    
  10. >>> f"{a:c}" # ascii 码    
  11. '*'   

5、格式化浮点数 

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

6、字符串对齐,so easy! 

  1. >>> x = 'test'    
  2. >>> f'{x:>10}'   # 右对齐,左边补空格    
  3. '      test'    
  4. >>> f'{x:*<10}'  # 左对齐,右边补*    
  5. 'test******'    
  6. >>> f'{x:=^10}'  # 居中,左右补=    
  7. '===test==='    
  8. >>> x, n = 'test', 10    
  9. >>> f'{x:~^{n}}' # 可以传入变量 n    
  10. '~~~test~~~'    
  11. >>>   

7、使用 !s,!r 

  1. >>> x = '中'    
  2. >>> f"{x!s}" # 相当于 str(x) 
  3. '中'    
  4. >>> f"{x!r}" # 相当于 repr(x)    
  5. "'中'"   

8、自定义格式 

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

输出如下: 

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

最后

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

以后关于字符串的格式化,就 f-string 了。如果觉得有收获,还请点赞、在看、关注,感谢支持! 

 

责任编辑:庞桂玉 来源: Python开发者
相关推荐

2022-02-15 16:51:57

Pythonf-strings字符串

2021-10-19 06:58:57

Python格式化f-strings

2023-02-10 08:13:56

Pythonf-strings

2023-09-12 16:55:26

Python语言PyPy

2019-04-03 16:32:38

OracleNetSuite可视性

2023-11-09 11:03:15

ChatGPTOpenAI

2020-08-13 14:45:08

微信腾讯财报

2020-08-27 14:37:12

先导杯

2019-10-12 09:23:31

网络安全人生第一份工作软件

2011-12-12 10:47:02

2021-03-07 22:22:20

比特币金融安全

2013-12-09 11:23:19

百度联盟糗事百科

2023-09-05 08:22:44

Golangstrings 包

2017-04-07 16:30:51

Androidstrings.xml原则

2023-09-06 09:10:04

Golang字符串

2023-09-04 08:17:37

Golangstrings 包

2023-12-03 23:01:49

算法研究

2019-06-03 10:14:07

API网关微服务

2020-11-19 07:49:24

JS变量作用域

2022-09-25 23:37:48

比特币数字货币加密货币
点赞
收藏

51CTO技术栈公众号