键格式化多行字符串时换行符错误


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;
}

最新更新