【问题标题】:How does nested placeholder "{}" work in format language?嵌套占位符“{}”如何在格式语言中工作?
【发布时间】:2019-04-06 11:29:09
【问题描述】:

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


    【解决方案1】:

    根据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) 中,数字被打印在 @ 987654327@花括号(根据观察)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多