自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python 的 f-strings 作用遠超你的預期

開發(fā) 后端
學過 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、格式化浮點數(shù) 

  1. >>> num_value = 123.456    
  2. >>> f'{num_value = :.2f}' #保留 2 位小數(shù)    
  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 非常靈活優(yōu)雅,同時還是效率最高的字符串拼接方式:

以后關于字符串的格式化,就 f-string 了。如果覺得有收獲,還請點贊、在看、關注,感謝支持! 

 

責任編輯:龐桂玉 來源: Python開發(fā)者
相關推薦

2021-10-19 06:58:57

Python格式化f-strings

2022-02-15 16:51:57

Pythonf-strings字符串

2023-02-10 08:13:56

Pythonf-strings

2023-09-12 16:55:26

Python語言PyPy

2019-04-03 16:32:38

OracleNetSuite可視性

2025-03-28 04:30:00

2023-11-09 11:03:15

ChatGPTOpenAI

2019-10-12 09:23:31

網(wǎng)絡安全人生第一份工作軟件

2020-08-27 14:37:12

先導杯

2020-08-13 14:45:08

微信騰訊財報

2025-02-03 10:00:00

DeepSeekChatGPT人工智能

2021-03-07 22:22:20

比特幣金融安全

2011-12-12 10:47:02

2017-04-07 16:30:51

Androidstrings.xml原則

2023-09-06 09:10:04

Golang字符串

2023-09-04 08:17:37

Golangstrings 包

2023-09-05 08:22:44

Golangstrings 包

2013-12-09 11:23:19

百度聯(lián)盟糗事百科

2019-06-03 10:14:07

API網(wǎng)關微服務

2020-11-19 07:49:24

JS變量作用域
點贊
收藏

51CTO技術棧公眾號