Escape Curly Brace in f-String in Python

In this tutorial, we will see how to escape curly brace in f-string in Python.

Use of the f-string in Python

In Python, we can format strings using different methods to get the final result in our desired style and format. String formatting is also used for replacing and filling in missing values.

Python 3.6 introduced a new method to format strings called f-strings. The f-strings provide a quick and efficient way to format strings in Python. It is considered faster than the other methods of format() function and the % operator.

We will discuss how to escape curly braces in f-strings in Python in this tutorial.

How to escape curly brace in f-string in Python

First, let us understand what it means to escape a character. A character in a string can have some specific function and escaping here indicates a way to reduce the ambiguity and confusion so that the character is treated normally.

Now, we will discuss the use of curly braces in f-strings. With the curly braces, we can specify the values of a variable in a string.

See the code below.

Output:

Java 2 Blog

In the above example, we provide the value of the variable a using curly braces in the string literal.

Now, what if we need to escape curly braces in f-strings in Python. For this, there is a simple fix of using two curly braces instead of one. This way, we can print the curly braces in the output.

However, this way we cannot provide the missing values.

See the code below.

Output:

a 2 Blog

In the above example, we can see that instead of printing the value of variable a we only print its name.

To fix this, there is a need to introduce additional curly braces. So, in total, we are using three curly braces in such situations where we want to escape curly braces in f-strings in Python and print the variable’s value.

See the code below.

Output:

{Java} 2 Blog

Conclusion

In this tutorial, we discussed how to escape curly braces in f-strings in Python. We first discussed the basics of the f-strings and the use of the curly braces. We then discussed how to escape curly braces by using them twice as {{ and }}. We also discussed using curly braces thrice to escape them and print the missing values.

That’s all about how to escape curly brace in f-string in python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *