简体   繁体   English

格式化多行字符串时,换行上的keyError

[英]keyError on newline when format multi-lines string

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

Let's try string with multi-lines. 让我们尝试使用多行字符串。
The string i want to format it. 我要格式化的字符串。

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

Now to format it with some number. 现在用一些数字格式化它。

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

You should replace { with {{ / } with }} to mean { / } literally. 您应将{替换为{{ / } }}来表示{ / }字面意思。

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

prints: 打印:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM