Escape Curly Braces in F-String in Python

Escape Curly Braces in F-String in Python

Escape in programming means solving a problem with a character or string to get the desired output. This article will show how to print curly brackets in output using the f-string method.

Escape Curly Braces in F-String in Python

A function called f-string is introduced in Python 3.6 and its newer versions to format a string. The same function, format(), is used in older versions, but the f-string is faster and more concise than the format() method.

First, we will create an f-string. To create an f-string, precede the string you want to format with f, and then inside curly brackets, we have to specify the variable of that string which we want to format our own way.

Consider the following example:

#Python 3.x
a = 'programming'
print(f'{a} is fun!')

Output:

programming is fun!

As you can see, the string is formatted, but the problem is we cannot get the curly brackets in the output. So for this purpose, we will use double braces instead of one.

Use Double Curly Braces

Example:

#Python 3.x
a = 'programming'
print(f'{{a}} is fun!')

Output:

{a} is fun!

Now we see that curly brackets are printed in the output. Still, here we have encountered another problem: only the variable is printed in the output instead of the whole string contained by that variable.

To overcome this problem, we will use 3 braces in total.

Use Triple Curly Braces

Example:

#Python 3.x
a = 'programming'
print(f'{{{a}}} is fun!')

Output:

{programming} is fun!

We got our desired formatted string in the output along with curly brackets.

So to print curly brackets while using the f-string method, we need to use triple braces instead of one.

Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

LinkedIn

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python