---
tags: Python
---
# Formatted string literals (f-string)
[TOC]
[PEP498 Literal String Interpolation](https://www.python.org/dev/peps/pep-0498/) f-string 是 Python3.6 引入的新方法,可以先看 [Python 3's f-Strings: An Improved String Formatting Syntax (Guide)](https://realpython.com/python-f-strings/) ,有詳盡的範例。
* 相較於 `format` 更簡潔:
```python
'Hello, {name}. You are {age}.'.format(name=name, age=age)
```
```python
f'Hello, {name}. You are {age}.'
```
* 效能也更高,比 format 快了一倍。
> F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.
* pylint 需要升級到 2.x ,否則會被視為 `syntax-error` 。
expression 內變數未定義時, pylint 能夠正確抓到錯誤:`undefined-variable` 。
## datetime
```python
>>> import datetime
>>> now = datetime.datetime.now()
>>> f'{now}'
'2019-07-18 14:44:15.942799'
>>> f'{now!r}' # 表示 repr(),representation 會顯示更詳盡的資訊
'datetime.datetime(2019, 7, 18, 14, 44, 15, 942799)'
>>> f'{now:%r}'
'02:44:15 PM'
>>> f'{now:%X}'
'14:44:15'
>>> f'{now:%F}'
'2019-07-18'
```
更多格式可以看:[datetime - `strftime()` and `strptime()` Behavior](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior)
## 數字
```python
>>> value = 123.456
>>> f'{value:.2f}' # 小數點後兩位
'123.46'
>>> f'{value:8.2f}' # 靠右對齊,寬度為 8
' 123.46'
>>> f'{value:<8.2f}' # 靠左對齊,寬度為 8
'123.46 '
>>> f'{value:^8.2f}' # 置中對齊,寬度為 8
' 123.46 '
>>> f'{value:09.3f}' # 前面補零
'00123.456'
>>> f'{value:%}' # 以百分比的方式輸出
'12345.600000%'
>>> f'{value:+}' # 輸出包含正負號
'+123.456'
```
## for
```python
>>> for x in range(4):
>>> print(f"{'*' * x}")
*
**
***
>>> for x in range(4):
>>> print(f"{'*' * x:>4}") ## 靠右對齊
*
**
***
>>> for x in range(1, 6, 2):
>>> print(f"{'*' * x: ^5}") ## 置中對齊
*
***
*****
```
## Python3.8 Debugging
```python
>>> name = 'Celine'
>>> f'name = {name}' # No need anymore
>>> "name = 'Celine'"
>>> f'{name = }'
"name = 'Celine'"
>>> f'{name=}'
"name='Celine'"
```
## 參考資料
1. [Python 3's f-Strings: An Improved String Formatting Syntax (Guide)](https://realpython.com/python-f-strings/)
2. [f-string debugging in Python 3.8](https://tirkarthi.github.io/programming/2019/05/08/f-string-debugging.html)