How do I use text.format() when the text has curly braces from HTML CSS?

I have e.g. this code:

helpAbout = """
<!doctype html>
<style>
    td, th {padding: 0px 30px 0px 0px;}
</style>
<tr><td>Author:</td> <td>{}</td></tr>
"""
print(helpAbout.format(__author__))

which fails, because Python tries to insert __author__ where the curly braces from the CSS style command are.

I help myself by using the outdated ‘%’ formatting option.

helpAbout = """
<!doctype html>
<style>
    td, th  { padding: 0px 30px 0px 0px;}
</style>
<tr><td>Author:</td> <td>%s</td></tr>
"""
print(helpAbout % __author__)

This works. But I’d prefer to use the str.format() option consistently. Am i missing something or is it really true that str.format() has this shortcoming?

To insert literal curlies in a format string, double them:

<style>
    td, th {{padding: 0px 30px 0px 0px;}}
</style>
4 Likes

Oh, that easy. Many thanks!

It seems like you’ve run into a common issue with using curly braces in a string when using str.format(). To overcome this, you can use double curly braces {{ and }} to represent literal curly braces in your format string.

helpAbout = """
<!doctype html>
<style>
    td, th {{padding: 0px 30px 0px 0px;}}
</style>
<tr><td>Author:</td> <td>{}</td></tr>
"""
print(helpAbout.format(__author__))

This way, you can use str.format() consistently without any issues. I hope this explanation helps! For more details on HTML and CSS concepts, you can follow the below links

  1. W3School
  2. Iqra Technology