How To Format A String That Contains Curly Braces In Python?

Summary: Use one of the following methods to format strings that contain curly braces:

  • Use double curly braces {{}}
  • Use the old string formatting, i.e. the % operator
  • Use the JSON Library
  • Use Template Strings

Problem: Given a string literal with curly braces; how to format the string and ensure that the curly braces are available in the output?

To understand the problem statement, let us have a look at the following example:

Example:

x = "{Serial No.}{0} ".format(1)
print(x)

Output:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    x = "{Serial No.}{0} ".format(1)
KeyError: 'Serial No'

You can try this yourself in the interactive Python shell:

Exercise: Read the article and fix the bug!

From the above example it is clear that when we execute a print statement with a literal text that contains the curly braces, the program raises a KeyError unless we provide the proper syntax for string formatting. In this article, we shall be discussing the methods to overcome this problem and print our text with the curly braces along with string formatting. Therefore:

Desired Output:

{Serial No:}1

Before we dive into the solutions, let us have a look at the reason behind the KeyError exception.

KeyError Exception

A KeyError is raised when you try to access or look for a value in a dictionary that does not exist. For example, consider the following dictionary:

profile={
  'Name':'Shubham',
  'id':12345
}
print(profile['age'])

The above code will raise a KeyError exception. This is because we are trying to access the key ‘age‘ which does not exist within the dictionary profile. Since the key does not exist, we cannot access any value using this key.

Here’s what we get when we execute the above program:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    print(profile['age'])
KeyError: 'age'

No, the question that needs to be addressed is – “Why are we getting the KeyEror while formatting a string that contains a text along with curly braces?”

Reason: The .format() generally expects things inside { } to be keys but in this case, it is unable to do so since ‘Serial No.' is not a key. Therefore .format() unable to parse the data. This results in a KeyError as we are trying to access a key-value that does not exist.

Now that we know why we are getting the KeyError let us dive into the solutions to avoid this error.

Method 1: Using Double Curly Braces

We already discussed that {} inside a format string are special characters, therefore if we want to include braces as a part of our literal text, we need to tell the .format string parser that the given curly braces must be escaped and considered as a part of the given text literal. This can be easily done by doubling the curly braces encompassing the string, that is using the following syntax: {{Serial No.}}

The following program denotes how we can use double curly braces to reach our solution:

x = "{{Serial No.}}{0} ".format(1)
print(x)

Output:

{Serial No.}1 

Method 2: Using The Old String Formatting Style (%)

If you do not want to use the double curly braces then you might fancy the old style of string formatting that uses the modulo (%) operator. Let us have a look at the following program to understand how we can use the modulo operator to print our string along with curly braces in it.

x = " {Serial No.}%s"
print (x%(1)) 

Output

{Serial No.}1

Method 3: Using The JSON Library

In situations where you need to deal with complex JSON strings, the most efficient method of dealing with such scenarios is to use the JSON library in your program.

★ The json.dumps() method is used to covert a Python object, like a dictionary, to a JSON string.

Consider the following example which explains how we can use the JSON library to print JSON strings:

import json


group = "Admin"
id = 1111
x = {"ID" : id, "Group" : group}
print(json.dumps(x))

Output:

{"ID": 1111, "Group": "Admin"}

Have a look at the following snippet given below to compare and contrast how complex and messy the syntax becomes when we try to print the same string using {{}} in our program.

group = "Admin"
id = 1111
print('{{"ID": {}, "Group": {}}}'.format(id,group))

Output:

{"ID": 1111, "Group": Admin}

Method 4: Using Template Strings

Template strings are used to provide string substitutions. If you want to avoid extra curly braces and % based substitutions then you can use the Template class of the string module.

★ The substitute() method performs template substitution and returns a new string.

Disclaimer: This might be a little confusing and prone to several exceptions if not properly used which is why I personally do not recommend you to use this procedure unless absolutely necessary.

Let us have a look at the following program to understand the usage of Template strings:

from string import Template
x = Template("$open Serial No: $close")
x = x.substitute(open='{',close='}')
print('{} {}'.format(x,1))

Output:

{ Serial No: } 1

EXERCISE

Now let’s get our hands dirty and practice some coding. Can you guess the output of the following snippet?

Note: Make sure you follow the comments in the given snippet which will unlock an important concept for you!

greet = "HELLO FINXTER"
name = input("Enter Your Name: ")
age = input("Enter Your Age:")
print("\n")
#  to resolve an expression in the brackets instead of using literal text use three sets of curly braces
print(f"{{{greet.lower()}}} {name}")
print('{{You are {} years old!}}'.format(age))

Conclusion

In this article, we discussed various methods to format a string that contains curly braces in Python. Frankly speaking, the double curly braces is the simplest solution while using the JSON Library is the most efficient method while dealing with complex JSON data. However, you are always free to use any method that suits your requirements and the best way of getting hold of all these techniques is to practice them. So without further delay, please try them in your system, and please feel free to drop queries.

Please subscribe and stay tuned for more interesting articles!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!