【问题标题】:Problem with string formatting when using triple quotes in Python [duplicate]在 Python 中使用三引号时出现字符串格式问题 [重复]
【发布时间】:2021-12-17 20:17:40
【问题描述】:

为此,

name='the name'
address='the address'

s = '''{
  "name": "{0}",
  "address": "{1}"
}
'''
print(s.format(name, address))

我希望它会打印以下内容。

{
  "name": "the name",
  "address": "the address"
}

但是我得到了以下错误。为什么以及解决方案是什么?

KeyError                                  Traceback (most recent call last)
<ipython-input-8-eb4c74e2dd68> in <module>
      8 '''
      9 
---> 10 print(s.format(name, address))

KeyError: '\n  "name"'

【问题讨论】:

标签: python string string-formatting


【解决方案1】:

外部{} 需要转义以进行字符串格式化,您可以通过将{ } 加倍来实现。

s = '''{{
  "name": "{0}",
  "address": "{1}"
}}
'''

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    • 2017-06-11
    • 2020-08-11
    • 2023-03-05
    相关资源
    最近更新 更多