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

王林
發布: 2023-04-18 19:22:03
轉載
1059 人瀏覽過

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

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

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 作用遠遠超出你的預期

以後關於字串的格式化,就f-string 了。如果覺得有收穫,也請按讚、在看、關注,感謝支持!

以上是Python 的 f-strings 作用遠遠超出你的預期的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:51cto.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!