python-3.x - 嵌套占位符“{}”如何在格式语言中工作?
问题描述
我不太了解格式化语言中嵌套占位符 {} 的工作原理。str.format()
例子:
>>> '{{{}}}{{{}}}'.format(25, 10)
'{25}{10}'
>>> '{{}}{{}}'.format(25, 10)
'{}{}'
>>> '{{{}}}{{}}'.format(25, 10)
'{25}{}'
>>> '{{{}}}{{{}}}'.format(25, 10)
'{25}{10}'
>>> '{{{{}}}}{{{}}}'.format(25, 10)
'{{}}{25}'
>>> '{{{{{}}}}}{{{}}}'.format(25, 10)
'{{25}}{10}'
有人可以逐步向我解释如何评估占位符吗?
解决方案
根据 python 文档https://docs.python.org/3.4/library/string.html#format-string-syntax
Format strings contain “replacement fields” surrounded by curly braces {}.
Anything that is not contained in braces is considered literal text, which is
copied unchanged to the output. If you need to include a brace character in the
literal text, it can be escaped by doubling: {{ and }}.
一个更简单的例子来理解它
>>> '{}'.format(25)
'25'
>>> '{{}}'.format(25)
'{}'
>>> '{{{}}}'.format(25)
'{25}'
>>> '{{{{}}}}'.format(25)
'{{}}'
>>> '{{{{{}}}}}'.format(25)
'{{25}}'
>>> '{{{{{{}}}}}}'.format(25)
'{{{}}}'
每当您看到偶数个(n)
大括号时,大括号就会被转义并且数字不会被打印出来,我们会得到n/2
大括号,但是在奇数个(n)
大括号中,数字会打印在(n-1)/2
大括号周围(基于观察)
类似的想法可以在上面的例子中看到
推荐阅读
- php - 实现 Symfony 的 UserInterface 的 DDD 和用户实体的设计问题
- c++ - 使用 -Waddress 时检查 C++14 中的函数模板有效性
- node.js - 代理服务器收到来自上游服务器的无效响应。节点JS
- python - 带有 subprocess.run() 脚本的 Oarsub 作业
- excel - UDF 在工作簿中创建指向位置的超链接
- sql - SQL 电话号码从 xxx-xxx-xxxx 转换为 (xxx) xxx-xxx
- html - 溢出-y 滚动条在边缘留有空隙
- python - 从自定义回调中获取 Keras 模型输入
- html - 在文件名称中有空格的电子邮件正文中插入图片
- android - ListView:单击后将列表项保持在同一位置