DEV Community

Hugo Martins
Hugo Martins

Posted on • Originally published at hugomartins.io on

3 2

How to Escape { in Python

Last week, I was faced with an intriguing question. How do I escape { when using str.format in Python?

str.format(*args, **kwargs) is a function that can be used to perform string formatting. Explicit, huh? A simple example of using str.format is:

    >>> "Hello {}!".format("World")
    'Hello World!'
Enter fullscreen mode Exit fullscreen mode

But…what if you need to format a string that actually has the character { in it, such as a “Hello {World}!”? It is actually fairly simple. From Format String Syntax:

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: **{{** and **}}**.

So, our initial example would be:

    >>> "Hello {{{}}}!".format("World")
    'Hello {World}!'
Enter fullscreen mode Exit fullscreen mode

That’s right, you need 3 braces! {{ turns into { once the string is formatted, }} turns into } once the string is formatted and the middle {} are the braces that actually allow you to dynamically format the string.

A few more examples:

    >>> "Hello {{{}}}!".format("World")
    'Hello {World}!'
    >>> "{{".format("World")
    '{'
    >>> "}}".format("World")
    '}'
    >>> "{}".format("World")
    'World'
Enter fullscreen mode Exit fullscreen mode

It turns out that this is much simpler than I thought it would be. It took me a lot more time to find out. I assume that was because I wasn’t using the appropriate keywords and I ended up reading the manual - which is what I should have done in the first place.

P.S.: Immediately after this, I found the following StackOverflow answers, explaining exactly the same.

Originally published at https://hugomartins.io on November 11, 2019.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay