![]() |
|
[Tut] How To Format A String That Contains Curly Braces In Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How To Format A String That Contains Curly Braces In Python? (/thread-97440.html) |
[Tut] How To Format A String That Contains Curly Braces In Python? - xSicKxBot - 09-25-2020 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: 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. |