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

Python 的 f-strings 作用遠(yuǎn)超你的預(yù)期

開發(fā) 后端
學(xué)過 Python 的朋友應(yīng)該都知道 f-strings 是用來非常方便的格式化輸出的,覺得它的使用方法無外乎就是 print(f'value = { value }',其實(shí),f-strings 遠(yuǎn)超你的預(yù)期,今天來梳理一下它還能做那些很酷的事情。

學(xué)過 Python 的朋友應(yīng)該都知道 f-strings 是用來非常方便的格式化輸出的,覺得它的使用方法無外乎就是 print(f'value = { value }',其實(shí),f-strings 遠(yuǎn)超你的預(yù)期,今天來梳理一下它還能做那些很酷的事情。

1、懶得再敲一遍變量名

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

2、直接改變輸出結(jié)果

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 進(jìn)制輸出真的太簡(jiǎn)單

>>> a = 42  
>>> f"{a:b}" # 2進(jìn)制
'101010'
>>> f"{a:o}" # 8進(jìn)制
'52'
>>> f"{a:x}" # 16進(jìn)制,小寫字母
'2a'
>>> f"{a:X}" # 16進(jìn)制,大寫字母
'2A'
>>> f"{a:c}" # ascii 碼
'*'

5、格式化浮點(diǎn)數(shù)

>>> num_value = 123.456  
>>> f'{num_value = :.2f}' #保留 2 位小數(shù)
'num_value = 123.46'
>>> nested_format = ".2f" #可以作為變量
>>> print(f'{num_value:{nested_format}}')
123.46

6、字符串對(duì)齊,so easy!

>>> x = 'test'  
>>> f'{x:>10}' # 右對(duì)齊,左邊補(bǔ)空格
' test'
>>> f'{x:*<10}' # 左對(duì)齊,右邊補(bǔ)*
'test******'
>>> f'{x:=^10}' # 居中,左右補(bǔ)=
'===test==='
>>> x, n = 'test', 10
>>> f'{x:~^{n}}' # 可以傳入變量 n
'~~~test~~~'
>>>

7、使用 !s,!r

>>> x = '中'  
>>> f"{x!s}" # 相當(dāng)于 str(x)
'中'
>>> f"{x!r}" # 相當(dāng)于 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 非常靈活優(yōu)雅,同時(shí)還是效率最高的字符串拼接方式:

以后關(guān)于字符串的格式化,就 f-string 了。如果覺得有收獲,還請(qǐng)點(diǎn)贊、在看、關(guān)注,感謝支持!

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

2021-10-19 06:58:57

Python格式化f-strings

2021-12-09 15:25:15

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)絡(luò)安全人生第一份工作軟件

2020-08-27 14:37:12

先導(dǎo)杯

2020-08-13 14:45:08

微信騰訊財(cái)報(bào)

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-05 08:22:44

Golangstrings 包

2023-09-06 09:10:04

Golang字符串

2023-09-04 08:17:37

Golangstrings 包

2013-12-09 11:23:19

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

2019-06-03 10:14:07

API網(wǎng)關(guān)微服務(wù)

2020-11-19 07:49:24

JS變量作用域
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)