• 欢迎光临~

# f-strings: Python字符串处理的瑞士军刀

f-string在本质上并不是字符串常量，而是一个在运行时运算求值的表达式。

### 变量嵌入 & 变量拼接

``````name = "Tom"

print(f"I'm {name}")
# I'm Tom
``````

### 表达式求值

``````print(f"3 x 2 = {3*2}")
# 3 x 2 = 6

print(f"{3 * 2 = }")
# 3 * 2 = 6
``````

### 调用函数

``````name = "Tom"

print(f"I'm {name.lower()}")
# I'm tom
``````

### 多行string

``````name, job = "tom", "student"

s = f"""I'm {name.capitalize()},
and I'm a {job.capitalize()}"""

print(s)
"""
I'm Tom,
and I'm a Student
"""
``````

### 对齐

``````Syntax: {:[width][.precision][type]}
``````

• `<`：左对齐
• `>`：右对齐（默认）
• `^`：居中对齐
``````word = "python"

>>> f"|{word:<10}|"
'|python    |'

>>> f"|{word:>10}|"
'|    python|'

>>> f"|{word:^10}|"
'|  python  |'
``````

``````# 本例用小数点来补全空余内容
>>> f"|{word:.<10}|"
'|python....|'

>>> f"|{word:.>10}|"
'|....python|'

>>> f"|{word:.^10}|"
'|..python..|'
``````

``````year, month, day = 2022, 1, 1

>>> f"{year}-{month:0>2}-{day:0>2}"
'2022-01-01'
``````

### 数字格式化

``````Syntax: {:[width][.precision][type]}
``````

type：

• s：字符串格式（默认）
• d：整型
• e：科学计数，默认precision为6
• f：浮点数，默认precision为6
• %：百分比格式，默认浮点数格式，外加百分比格式化

#### 浮点数精度格式化

``````pi = 3.141592654
print(f"PI = {pi:.2f}")
# PI = 3.14

print(f"PI = {pi:.3f}")
# PI = 3.142
``````

#### 科学计数

``````print(f"{pi:e}")
# 3.141593e+00

print(f"{pi:.2e}")
# 3.14e+00
``````

#### 百分比格式化

``````print(f"PI = {pi:.3%}")
# PI = 314.159%

print(f"PI = {pi:.2%}")
# PI = 314.16%
``````

#### 千位分隔符

``````>>> f"{234234234:,}"
'234,234,234'

>>> f"{234234234.1314:,.2f}"
'234,234,234.13'
``````

### 进制转换

``````num = 23
bin(num)	# '0b10111'
oct(num)	# '0o27'
hex(num)	# '0x17'
``````

``````f"{num:b}"	# '10111'
f"{num:o}"	# '27'
f"{num:d}"	# '23'
f"{num:x}"	# '17'
``````

``````f"{num:#b}"	# '0b10111'
f"{num:#o}"	# '0o27'
f"{num:#d}"	# '23'
f"{num:#x}"	# '0x17'
``````

### lambda表达式

``````>>> f"result is {(lambda x: x**2+1)(5)}"
'result is 26'
``````

### 日期格式化

``````today = datetime.datetime.today()
f"{today:%Y}"			# '2022'
f"{today:%Y-%m}"		# '2022-12'
f"{today:%Y-%m-%d}"		# '2022-12-16'

f"{today:%F}"		# '2022-12-16'
f"{today:%D}"		# '12/16/22'
f"{today:%X}"		# '21:01:27'
f"{today:%F %X}"	# '2022-12-16 21:01:27'
``````

### 参考

• python docs: Formatted string literals
• PEP 498 – Literal String Interpolation
• A Guide to Formatting with f-strings in Python
• A Simple Guide to String Formatting in Python Using f-strings