日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Python的f-strings作用遠(yuǎn)超你的預(yù)期

學(xué)過 Python 的朋友應(yīng)該都知道 f-strings 是用來非常方便的格式化輸出的,覺得它的使用方法無外乎就是 print(f'value = { value }',其實,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)制輸出真的太簡單

>>> 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、格式化浮點數(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、字符串對齊,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}" # 相當(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)雅,同時還是效率最高的字符串拼接方式:

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


分享題目:Python的f-strings作用遠(yuǎn)超你的預(yù)期
新聞來源:http://www.5511xx.com/article/djijics.html