惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
P
Palo Alto Networks Blog
S
Securelist
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
NISL@THU
NISL@THU
L
Lohrmann on Cybersecurity
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
C
Cisco Blogs
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
Recent Announcements
Recent Announcements
Simon Willison's Weblog
Simon Willison's Weblog
T
Tenable Blog
Know Your Adversary
Know Your Adversary
Spread Privacy
Spread Privacy
WordPress大学
WordPress大学
月光博客
月光博客
Latest news
Latest news
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threat Research - Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
I
InfoQ
D
Darknet – Hacking Tools, Hacker News & Cyber Security
W
WeLiveSecurity
Hacker News - Newest:
Hacker News - Newest: "LLM"
酷 壳 – CoolShell
酷 壳 – CoolShell
U
Unit 42
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
Google DeepMind News
Google DeepMind News
Apple Machine Learning Research
Apple Machine Learning Research
Attack and Defense Labs
Attack and Defense Labs
罗磊的独立博客
T
The Exploit Database - CXSecurity.com
I
Intezer
GbyAI
GbyAI
Jina AI
Jina AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
Google Online Security Blog
Google Online Security Blog
Engineering at Meta
Engineering at Meta
D
Docker
Recent Commits to openclaw:main
Recent Commits to openclaw:main
小众软件
小众软件
云风的 BLOG
云风的 BLOG
爱范儿
爱范儿
Project Zero
Project Zero

博客园 - 张高兴

张高兴的 Hailo-10 开发指南:(二)使用 LangChain 搭建本地大模型 RAG 问答应用 张高兴的 Hailo-10 开发指南:(一)实现离线语音识别 张高兴的大模型开发实战:(八)在 Dify 中使用 MCP 协议 张高兴的大模型开发实战:(七)基于 Dify + Ollama 搭建私有化知识问答助手 张高兴的大模型开发实战:(六)在 LangGraph 中使用 MCP 协议 为什么要对程序进行调试 张高兴的大模型开发实战:(五)使用 LLaMA Factory 微调与量化模型并部署至 Ollama 张高兴的大模型开发实战:(四)使用 LangGraph 实现多智能体应用 张高兴的大模型开发实战:(三)使用 LangGraph 为对话添加历史记录 张高兴的大模型开发实战:(二)使用 LangChain 构建本地知识库应用 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫 张高兴的 Raspberry Pi AI 开发指南:(三)将自定义模型编译为 Hailo NPU 的 .hef 模型 张高兴的 Raspberry Pi AI 开发指南:(二)使用 Python 和 HailoRT 进行实时目标检测 张高兴的 Raspberry Pi AI 开发指南:(一)Hailo-8 配置 张高兴的 MicroPython 入门指南:(三)使用串口通信 张高兴的 MicroPython 入门指南:(二)GPIO 的使用 张高兴的 MicroPython 入门指南:(一)环境配置、Blink、部署 如何安全地访问互联网 RowHammer 攻击:内存的隐形威胁 在 .NET 中使用 OPC UA 协议 张高兴的 .NET IoT 入门指南:(八)基于 GPS 的 NTP 时间同步服务器
🚀 Python f-string 全攻略:从入门到大师,让你的编码效率翻倍!
张高兴 · 2025-05-26 · via 博客园 - 张高兴

什么是 f-string

f-string 是 Python 3.6 引入的一种字符串格式化方法。通过在字符串前加 fF 前缀,直接在 {} 中嵌入变量或表达式。相比传统的 % 格式化和 str.format() 方法,f-string 执行速度更快,并且支持复杂的格式化操作,如数字精度控制、对齐、日期格式化等,甚至可用于代码调试。

基础用法

变量插值

name: str = "张三"
age: int = 25
print(f"我是{name},今年{age}岁。")
# 输出: 我是张三,今年25岁。

表达式嵌入

x, y = 10, 20
print(f"{x} + {y} = {x + y}")
# 输出: 10 + 20 = 30

调用函数

def square(n):
    return n ** 2

num = 5
print(f"{num} 的平方等于 {square(num)}")
# 输出: 5 的平方等于 25

数字格式化

千位分隔符

money = 1000000000
print(f"{money:,} 元")
# 输出: 1,000,000,000 元
print(f"{money:_} 元")
# 输出: 1_000_000_000 元

控制小数位数

pi = 3.1415926535
print(f"四舍五入到两位: {pi:.2f}")
# 输出: 四舍五入到两位: 3.14
print(f"四舍五入到整数: {pi:.0f}")
# 输出: 四舍五入到整数: 3

百分比转换

ratio = 0.75
print(f"百分比: {ratio:.2%}")
# 输出: 百分比: 75.00%

科学计数法

value = 0.0001234
print(f"科学计数法: {value:.2e}")
# 输出: 科学计数法: 1.23e-04

文本对齐与填充

填充对齐

text = "Python"
print(f"填充10字符左对齐: '{text:<10}'")      # 左对齐
# 输出: 填充20字符左对齐: 'Python              '
print(f"填充10字符右对齐: '{text:>10}'")      # 右对齐
# 输出: 填充20字符右对齐: '              Python'
print(f"填充10字符居中对齐: '{text:^10}'")    # 居中对齐
# 输出: 填充20字符居中对齐: '       Python       '

自定义填充字符

text = "Python"
print(f"{text:_^20}")
# 输出: _______Python_______
print(f"{text:#^20}")
# 输出: #######Python#######

日期时间格式化

from datetime import datetime

now = datetime.now()
print(f"日期: {now:%Y-%m-%d}")
# 输出: 日期: 2025-05-26
print(f"时间: {now:%H:%M:%S}")
# 输出: 时间: 15:01:15
print(f"当地时间: {now:%c}")
# 输出: 当地时间: Mon May 26 15:01:15 2025
print(f"12小时制: {now:%I%p}")
# 输出: 12小时制: 03PM

进阶技巧

嵌套 f-string

value = 42
print(f"{f'The value is {value}':^30}")
# 输出: '       The value is 42        '

动态格式化参数

width = 20
precision = 2
num = 3.14159
print(f"Pi: '{num:^{width}.{precision}f}'")
# 输出: Pi: '        3.14        '

表格对齐

print(f"{'ID':<5} {'Name':<10} {'Score':>6}")
print(f"1   {'Alice'}     {85.5:>6.2f}")
print(f"2   {'Bob'}       {92.0:>6.2f}")
# 输出:
# ID    Name        Score
# 1     Alice       85.50
# 2     Bob         92.00

自记录表达式(调试输出)

f-string 支持在花括号内使用 = 符号来输出表达式及其结果,这在调试时非常有用:

a, b = 10, 5
print(f"{a = }")  # 输出: a = 10
print(f"{a + b = }")  # 输出: a + b = 15
print(f"{a * b = }")  # 输出: a * b = 50
print(f"{bool(a) = }")  # 输出: bool(a) = True

与其他格式化方法的对比

方法 优点 缺点
% 格式化 语法简单 可读性差,不支持复杂格式化
str.format() 灵活性高 代码冗长
f-string 简洁、高效、可读性强 需 Python 3.6+