1. 程式人生 > 其它 >python3 格式化字串 f-string f'strsrtstr'

python3 格式化字串 f-string f'strsrtstr'

f-string,亦稱為格式化字串常量(formatted string literals),是Python3.6新引入的一種字串格式化方法,該方法源於PEP 498 – Literal String Interpolation,主要目的是使格式化字串的操作更加簡便。f-string在形式上是以f或F修飾符引領的字串(f'xxx'或F'xxx'),以大括號{}標明被替換的欄位;f-string在本質上並不是字串常量,而是一個在執行時運算求值的表示式

  1. name = 'Eric'
  2. f'Hello, my name is {name}'
  3. 輸出'Hello, my name is Eric'

自定義格式:對齊、寬度、符號、補零、精度、進位制等
f-string採用{content:format}設定字串格式,其中content是替換並填入字串的內容,可以是變數、表示式或函式等,format是格式描述符。採用預設格式時不必指定{:format},如上面例子所示只寫{content}即可。

>>> a = 123.456
>>> f'a is {a:8.2f}'
'a is 123.46'
>>> f'a is {a:08.2f}'
'a is 00123.46'
>>> f'a is {a:8.2e}'
'a is 1.23e+02
' >>> f'a is {a:8.2%}' 'a is 12345.60%' >>> f'a is {a:8.2g}' 'a is 1.2e+02' >>> s = 'hello' >>> f's is {s:8s}' 's is hello ' >>> f's is {s:8.3s}' 's is hel '

連結:https://blog.csdn.net/whatday/article/details/106729795