简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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