Search code examples
pythonstringpython-3.xformatquote

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'

Solution

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