f-string
想必很多Python
使用者都基礎性的使用過,作為Python
3.6版本開始引入的特性,通過它我們可以更加方便地向字串中嵌入自定義內容,但f-string
真正蘊含的功能遠比大多數使用者知道的要豐富,今天我們就來一起get它們~
- 最基礎用法
f-string
最基礎的用法很簡單,如下例所示,在字首f
的字串中向{}
內直接填入要嵌入的值、變數或計算表示式:

- 自記錄表示式
從Python
3.8版本開始,為f-string
引入了自記錄表示式,使得我們可以按照下面的寫法快速輸出一些計算表示式:

- 多行f-string
通過最外層包裹小括號,我們可以像下面這樣非常靈活地撰寫多行f-string
:

- 在f-string中格式化日期
針對日期型別的變數,我們可以參考下面的方式,直接在f-string
中快速地進行格式化:

- 控制浮點數精度
在f-string
中我們可以按照下列方式靈活地控制浮點數的小數位數:

- 標準化顯示寬度
當我們需要對f-string
列印內容的顯示最小寬度進行限制時,譬如列印出類似表格的結構,可以參考下面的例子:

- 修改為左對齊
f-string
預設為右對齊,就像上面的例子,但我們可以像下面這樣使用<
修改顯示模式為左對齊:

- 設定科學計數法格式
我們可以參考下面的方式實現指定位數的科學計數法顯示方式:

- 控制有效數字位數
通過下面的方式,我們還可以控制所顯示數字的有效數字位數,即從左開始第一個不為0的數字往右一共顯示的個數,當位數低於整數部分時會自動變成科學計數法格式:

以上就是本文的全部內容,歡迎在評論區分享你的觀點和意見~