首页 > 解决方案 > 嵌套占位符“{}”如何在格式语言中工作?

问题描述

我不太了解格式化语言中嵌套占位符 {} 的工作原理。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-3.xpython-3.7

解决方案


根据 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大括号周围(基于观察)

类似的想法可以在上面的例子中看到


推荐阅读