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

推荐订阅源

T
Tor Project blog
博客园 - 聂微东
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 【当耐特】
G
Google Developers Blog
J
Java Code Geeks
The Cloudflare Blog
Attack and Defense Labs
Attack and Defense Labs
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI
Cisco Talos Blog
Cisco Talos Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
I
Intezer
Jina AI
Jina AI
T
Tenable Blog
P
Palo Alto Networks Blog
Project Zero
Project Zero
D
DataBreaches.Net
Hugging Face - Blog
Hugging Face - Blog
The Hacker News
The Hacker News
F
Full Disclosure
Cloudbric
Cloudbric
量子位
H
Heimdal Security Blog
K
Kaspersky official blog
有赞技术团队
有赞技术团队
罗磊的独立博客
V
Vulnerabilities – Threatpost
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
阮一峰的网络日志
阮一峰的网络日志
Vercel News
Vercel News
Recent Announcements
Recent Announcements
WordPress大学
WordPress大学
GbyAI
GbyAI
S
SegmentFault 最新的问题
M
MIT News - Artificial intelligence
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
Recorded Future
Recorded Future
Security Archives - TechRepublic
Security Archives - TechRepublic
AI
AI
Webroot Blog
Webroot Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
The Exploit Database - CXSecurity.com
Apple Machine Learning Research
Apple Machine Learning Research
C
Cybersecurity and Infrastructure Security Agency CISA
H
Hacker News: Front Page
Latest news
Latest news

Jiajun的技术笔记

你好,2026! TiDB 源码阅读(六):TiDB Coprocessor 源码解析 性能优化的核心思想 TiDB 源码阅读(五):索引 TiDB 源码阅读(四):AST、逻辑计划、物理计划 CockroachDB Serverless Architecture podman 无故退出 Cursor Control-L (CTRL-L) Keyboard Shortcuts in Terminal Replace docker with podman Using xmonad with xfce4 A RC script for freebsd frpc 自己动手写一个k8s controller AI 会取代你的(编程)岗位吗? 自建DERP服务器提升Tailscale连接速度(使用Nginx转发) 自动升级Docker容器 再读《程序员修炼之道-从小工到专家》 让浏览器下载文件 再读《软件随想录》/《黑客与画家》/《软技能》 HTTP 压力测试中的 Coordinated Omission 2的补码 编程语言中的 context 是什么? flutter macOS 构建出错 Flatpak 使用小记 Golang CAS 操作是怎么实现的 PostgreSQL 当MQ来使用 Clash 结合 工作VPN 的网络设计 使用 PostgreSQL 搭建 JuiceFS PostgreSQL 配置优化和日志分析 有GitHub Copilot?那就可以搭建你的ChatGPT4服务 窗口函数的使用(以PG为例) 读《为什么学生不喜欢上学》 OpenAI Prompt Engineering 摘录和总结 读《打造真正的新产品》 VueJS 总结 Linux 自动挂载 alist 提供的webdav FreeBSD 使用 vm-bhyve 安装Debian虚拟机 FreeBSD 和 Linux 网卡聚合实现提速 GPT 帮我搞定了时区转换问题 长任务系统如何处理? macOS/Linux 编译 InputLeap 使用开源软KVM - synergy-core 解决 macOS 终端hostname一直变化问题 KVM 共享 Intel 集成显卡 PromQL 备忘 读《格鲁夫给经理人的第一课》 读《打开心智》 为什么要把复杂的联表操作拆成多个单表查询? 红包系统的设计 MySQL Index Condition Pushdown Optimization Go mod 简明教程 OpenWRT 使用 Android/iOS USB 网络 搭建旁路由 Golang gRPC 错误处理 编写可维护的单元测试代码 OAuth 2 详解(六):Authorization Code Flow with PKCE OAuth 2 详解(五):Device Authorization Flow OAuth 2 详解(三):Resource Owner Password Credentials Grant OAuth 2 详解(四):Client Credentials Flow OAuth 2 详解(二):Implict Grant Flow OAuth 2 详解(一):简介及 Authorization Code 模式 ElasticSearch 学习笔记 三种git流程以及发版模型 错误处理实践 权限模型(RBAC/ABAC) OIDC(OpenID Connect) 简介 任务队列简介 PostgreSQL 操作笔记 使用Drone CI构建CI/CD系统 Golang migrate 做数据库变更管理 使用PostgreSQL做搜索引擎 Nginx 源码阅读(三): 连接池、内存池 Nginx 源码阅读(二): 请求处理 Nginx 源码阅读(一): 启动流程 Go 泛型简明教程 KVM 显卡穿透给 Windows 使用 HTTP Router 处理 Telegram Bot 按钮回调 使用反射(reflect)对结构体赋值 GIN 是如何绑定参数的 你好 2022(2021 年终总结) 用Go导入大型CSV到PostgreSQL 使用 OpenWRT 搭建软路由 使用软KVM切换器 barrier 共享键鼠 SQL 防注入及原理 使用 gomock 测试 Go 代码 gevent不是黑魔法(二): gevent 实现 gevent不是黑魔法(一): greenlet 实现 用 entgo 替代 gorm 应用内使用crontab不是那么方便 单测时要不要 mock 数据库? Sentry 自建指南 用selenium完成自动化任务 用闲置的安卓手机做垃圾电话短信过滤 推荐三个时间管理工具 一次事故反思 当JS遇到uint64:JS整数溢出问题 SQLite3 存储以及ACID原理 Redis源码阅读:pub/sub实现 Redis源码阅读:zset实现 Redis源码阅读:bitmap 位图的运算 Redis源码阅读:set是怎么做交并集运算的?
Python字符串格式化
2017-04-16 · via Jiajun的技术笔记

说来惭愧,用Python这么久了,还没有系统的看过字符串格式化的文档,因为常用的也就 那么几个。这篇文章就总结一下Python的字符串格式化。

format() 方法

https://docs.python.org/3.4/library/string.html#format-string-syntax

先来看一下文档:

In [1]: format?
Docstring:
format(value[, format_spec]) -> string

Returns value.__format__(format_spec)
    format_spec defaults to ""
    Type:      builtin_function_or_method

format方法会替换value中 {} 包围的内容,其他字符直接拷贝过去不变。

具体允许的语法为:

"{" [field_name] ["!" conversion] [":" format_spec] "}"

其中 field_name 可以为空,为数字,为变量名,分别对应用法:

In [1]: "{}".format(1)
Out[1]: '1'

In [2]: "{0}{1}{2}".format(1, 2, 3)
Out[2]: '123'

In [3]: "{0}{1}{0}".format(1, 2)
Out[3]: '121'

In [4]: "{hello} world".format(hello="hello")
Out[4]: 'hello world'

并且 field_name 后可以接变量属性名,或者index,例如:

In [1]: class MyObject(object):
    ...:     val = 1
    ...:

In [2]: myobj = MyObject()

In [3]: "{.val}".format(myobj)
Out[3]: '1'

In [4]: "{0.val}".format(myobj)
Out[4]: '1'

In [5]: "{myobj.val}".format(myobj=myobj)
Out[5]: '1'
In [6]: atuple = (1, 2)

In [7]: "{0[1]}{0[0]}".format(atuple)
Out[7]: '21'

但是不可以使用字典里的值,因为引用字典中的值需要使用 adict["key"] 的形式, 会把当前字符格式打乱掉。其中上面所说的接点号进行属性引用调用 getattr,接 index引用调用 __getattr__

conversion有三个选项:

- `s` 将调用 `str()`
- `r` 将调用 `repr()`
- `a` 将调用 `ascii()` (Python 3才有)
In [1]: class MyObject(object):
   ...:     def __str__(self):
   ...:         return "__str__ been called"
   ...:     def __repr__(self):
   ...:         return "__repr__ been called"
   ...:

In [2]: myobj = MyObject()

In [3]: "{!r}".format(myobj)
Out[3]: '__repr__ been called'

In [4]: "{!s}".format(myobj)
Out[4]: '__str__ been called'

In [5]: "{!a}".format(myobj)
Out[5]: '__repr__ been called'

其中 {!a} 在调用完 repr() 之后把非ascii字符替换掉。

之后接 :,冒号之后是具体如何展现这个值,文档在:

https://docs.python.org/3.4/library/string.html#format-specification-mini-language

其格式为:[[fill]align][sign][#][0][width][,][.precision][type]

其中fill为填充空格的字符,默认不填则为空格,align可以是<>=^分别意味着向左靠齐, 向右靠齐,强制把正负号放在最左边,居中。

In [1]: "{:a>#30.4f}".format(3.1415926)
Out[1]: 'aaaaaaaaaaaaaaaaaaaaaaaa3.1416'

In [2]: "{:a<#30.4f}".format(3.1415926)
Out[2]: '3.1416aaaaaaaaaaaaaaaaaaaaaaaa'

In [3]: "{:a^#30.4f}".format(3.1415926)
Out[3]: 'aaaaaaaaaaaa3.1416aaaaaaaaaaaa'

In [4]: "{:a=#30.4f}".format(3.1415926)
Out[4]: 'aaaaaaaaaaaaaaaaaaaaaaaa3.1416'

In [5]: "{:a=#30.4f}".format(-3.1415926)
Out[5]: '-aaaaaaaaaaaaaaaaaaaaaaa3.1416'

逗号代表是否把整数每三位插一个逗号表示:

In [8]: "{:a=#30,.4f}".format(-300987.1415926)
Out[8]: '-aaaaaaaaaaaaaaaaa300,987.1416'

最后一位type可以是:

- `b` 二进制
- `c` 字符
- `d` 十进制
- `o` 八进制
- `x` 小写十六进制
- `X` 大写十六进制
- `n` 数字,和 `d` 一致不过会根据locale不同而改变

最后如果想在这里面表示双括号自己怎么办?

In [1]: "{{}}".format()
Out[1]: '{}'

In [2]: "{{".format()
Out[2]: '{'