09-25-2020, 04:51 PM
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:
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:
Output:
From the above example it is clear that when we execute astatement with a literal text that contains the curly braces, the program raises a 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:
Before we dive into the solutions, let us have a look at the reason behind the exception.
KeyError Exception
Ais raised when you try to access or look for a value in a dictionarythat does not exist. For example, consider the following dictionary:
The above code will raise aexception. This is because we are trying to access the key ‘‘ which does not exist within the dictionary . 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:
No, the question that needs to be addressed is – “Why are we getting the while formatting a string that contains a text along with curly braces?”
Reason: The generally expects things inside { } to be keys but in this case, it is unable to do so since ‘ is not a key. Therefore unable to parse the data. This results in a as we are trying to access a key-value that does not exist.
Now that we know why we are getting thelet 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:
The following program denotes how we can use double curly braces to reach our solution:
Output:
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.
Output
Method 3: Using The JSON Library
In situations where you need to deal with complexstrings, the most efficient method of dealing with such scenarios is to use the library in your program.
★ Themethod 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:
Output:
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.
Output:
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 theclass of the module.
★ The method performs template substitution a 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 ofstrings:
Output:
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!
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 subscribeand stay tunedfor 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!
The post How To Format A String That Contains Curly Braces In Python? first appeared on Finxter.
Summary: Use one of the following methods to format strings that contain curly braces:
- Use double curly braces Code:
{{}}
- 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:
Code:
x = "{Serial No.}{0} ".format(1)
print(x)Output:
Code:
Traceback (most recent call last): File "main.py", line 1, in <module> x = "{Serial No.}{0} ".format(1)
KeyError: 'Serial No'From the above example it is clear that when we execute a
Code:
printCode:
KeyErrorDesired Output:
Code:
{Serial No:}1Before we dive into the solutions, let us have a look at the reason behind the
Code:
KeyErrorKeyError Exception
A
Code:
KeyErrorCode:
profile={ 'Name':'Shubham', 'id':12345
}
print(profile['age'])The above code will raise a
Code:
KeyErrorCode:
ageCode:
profileHere’s what we get when we execute the above program:
Code:
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
Code:
KeyErorReason: The
Code:
.format()Code:
Serial No.'Code:
.format()Code:
KeyErrorNow that we know why we are getting the
Code:
KeyErrorMethod 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:
Code:
{{Serial No.}}The following program denotes how we can use double curly braces to reach our solution:
Code:
x = "{{Serial No.}}{0} ".format(1)
print(x)Output:
Code:
{Serial No.}1If you do not want to use the double curly braces then you might fancy the old style of string formatting that uses the modulo (
Code:
%)Code:
x = " {Serial No.}%s"
print (x%(1))Output
Code:
{Serial No.}1In situations where you need to deal with complex
Code:
JSONCode:
JSON★ The
Code:
json.dumps()Consider the following example which explains how we can use the JSON library to print JSON strings:
Code:
import json group = "Admin"
id = 1111
x = {"ID" : id, "Group" : group}
print(json.dumps(x))Output:
Code:
{"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.
Code:
group = "Admin"
id = 1111
print('{{"ID": {}, "Group": {}}}'.format(id,group))Output:
Code:
{"ID": 1111, "Group": Admin}Template strings are used to provide string substitutions. If you want to avoid extra curly braces and % based substitutions then you can use the
Code:
TemplateCode:
string★ The
Code:
substitute()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
Code:
TemplateCode:
from string import Template
x = Template("$open Serial No: $close")
x = x.substitute(open='{',close='}')
print('{} {}'.format(x,1))Output:
Code:
{ Serial No: } 1EXERCISE
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!
Code:
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))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 subscribeand stay tunedfor 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!
The post How To Format A String That Contains Curly Braces In Python? first appeared on Finxter.

