python - 格式化多行字符串时换行符出现 keyError

标签 python string python-3.x format quote

print("xy{0}z".format(100))
xy100z

让我们尝试一下多行字符串。
我想要格式化它的字符串。

strs='''  
.item{0}{  
    background-image:url("img/item{0}_1.jpg");  
    background-repeat: no-repeat;  
    background-position: 0px 0px;  
}'''  

>>> print(strs)

.item{0}{
    background-image:url("img/item{0}_1.jpg");
    background-repeat: no-repeat;
    background-position: 0px 0px;
}

现在用一些数字来格式化它。

print(strs.format(100))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '\n    background-image'

最佳答案

您应该将 { 替换为 {{/} 替换为 }} 来表示 {/} 字面意思。

strs='''
.item{0}{{
    background-image:url("img/item{0}_1.jpg");
    background-repeat: no-repeat;
    background-position: 0px 0px;
}}'''  
print(strs.format(100))

打印:

.item100{
    background-image:url("img/item100_1.jpg");
    background-repeat: no-repeat;
    background-position: 0px 0px;
}

关于python - 格式化多行字符串时换行符出现 keyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43971564/

相关文章:

regex - 解析字符串并在perl中执行操作

python - 从嵌套字典/json 中删除键

Python 3 类(class),在打印语句末尾的句点之前有额外空间问题

python - Scrapy:无法检索App Store的评论页面

python - 如何使 Bokeh 散点图具有交互性(带 slider )

c - 使用 C 预处理器为 scanf 构造字符串文字?

java - JSONObject(String) 丢失?

python - 异步 python : How to call object methods in coroutines?

python - 如何获取任意编码的所有字符?

python - 在 Python 3.x 下将字符串传递给 ctypes 函数