Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How To Format A String That Contains Curly Braces In Python?

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

<div><p><strong>Summary: </strong>Use one of the following methods to format strings that contain curly braces:</p>
<ul>
<li>Use double curly braces <code>{{}}</code></li>
<li>Use the old string formatting, i.e. the % operator</li>
<li>Use the JSON Library</li>
<li>Use Template Strings</li>
</ul>
<p><strong>Problem:</strong> Given a string literal with curly braces; how to format the string and ensure that the curly braces are available in the output?</p>
<p>To understand the problem statement, let us have a look at the following example: </p>
<p><strong>Example: </strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = "{Serial No.}{0} ".format(1)
print(x)</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Traceback (most recent call last): File "main.py", line 1, in &lt;module&gt; x = "{Serial No.}{0} ".format(1)
KeyError: 'Serial No'</pre>
<p>From the above example it is clear that when we execute a <code>print </code>statement with a literal text that contains the curly braces, the program raises a <code>KeyError</code> unless we provide the proper syntax for <a href="https://blog.finxter.com/python-strings-format-specification-mini-language/" target="_blank" rel="noreferrer noopener">string formatting</a>. 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:</p>
<p><strong>Desired Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{Serial No:}1</pre>
<p>Before we dive into the solutions, let us have a look at the reason behind the <code>KeyError</code> exception.</p>
<h2>KeyError Exception</h2>
<p>A <code>KeyError </code>is raised when you try to access or look for a value in a <a href="https://blog.finxter.com/category/python-dictionary/" target="_blank" rel="noreferrer noopener">dictionary </a>that does not exist. For example, consider the following dictionary:</p>
<pre class="wp-block-code"><code>profile={ 'Name':'Shubham', 'id':12345
}
print(profile['age'])</code></pre>
<p>The above code will raise a <code>KeyError </code>exception. This is because we are trying to access the key ‘<code>age</code>‘ which does not exist within the dictionary <code>profile</code>. Since the key does not exist, we cannot access any value using this key.</p>
<p>Here’s what we get when we execute the above program: </p>
<pre class="wp-block-code"><code>Traceback (most recent call last): File "main.py", line 8, in &lt;module&gt; print(profile['age'])
KeyError: 'age'</code></pre>
<p>No, the question that needs to be addressed is – <em>“Why are we getting the <code>KeyEror</code></em> <em>while formatting a string that contains a text along with curly braces?”</em></p>
<p><strong>Reason: </strong>The <code>.format()</code> generally expects things inside { } to be keys but in this case, it is unable to do so since ‘<code>Serial No.'</code> is not a key. Therefore <code>.format()</code> unable to parse the data. This results in a <code>KeyError </code>as we are trying to access a key-value that does not exist. </p>
<p>Now that we know why we are getting the<code> KeyError </code>let us dive into the solutions to avoid this error.</p>
<h2>Method 1: Using Double Curly Braces </h2>
<p>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.}} </code></p>
<p>The following program denotes how we can use double curly braces to reach our solution:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = "{{Serial No.}}{0} ".format(1)
print(x)</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{Serial No.}1 </pre>
<h2>Method 2: Using The Old <a href="https://blog.finxter.com/string-formatting-vs-format-vs-formatted-string-literal/" target="_blank" rel="noreferrer noopener">String Formatting Style</a> (%)</h2>
<p>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 (<code>%)</code> 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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = " {Serial No.}%s"
print (x%(1)) </pre>
<p><strong>Output</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{Serial No.}1</pre>
<h2>Method 3: Using The JSON Library</h2>
<p>In situations where you need to deal with complex <a href="https://blog.finxter.com/how-to-parse-json-in-a-python-one-liner/" target="_blank" rel="noreferrer noopener"><code>JSON </code>strings</a>, the most efficient method of dealing with such scenarios is to use the <code>JSON </code>library in your program. </p>
<p>★ The<code> json.dumps() </code>method is used to covert a Python object, like a dictionary, to a JSON string. </p>
<p>Consider the following example which explains how we can use the JSON library to print JSON strings:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import json group = "Admin"
id = 1111
x = {"ID" : id, "Group" : group}
print(json.dumps(x))</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{"ID": 1111, "Group": "Admin"}</pre>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">group = "Admin"
id = 1111
print('{{"ID": {}, "Group": {}}}'.format(id,group))</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{"ID": 1111, "Group": Admin}</pre>
<h2>Method 4: Using Template Strings</h2>
<p><a href="https://docs.python.org/3.3/library/string.html#template-strings" target="_blank" rel="noreferrer noopener">Template strings</a> are used to provide string substitutions. If you want to avoid extra curly braces and % based substitutions then you can use the <code>Template </code>class of the <code>string</code> module. </p>
<p>★ The <code>substitute()</code> method performs template substitution a returns a new string. </p>
<p><strong>Disclaimer:</strong> 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. </p>
<p>Let us have a look at the following program to understand the usage of <code>Template </code>strings:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from string import Template
x = Template("$open Serial No: $close")
x = x.substitute(open='{',close='}')
print('{} {}'.format(x,1))</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{ Serial No: } 1</pre>
<p><strong>EXERCISE</strong></p>
<p>Now let’s get our hands dirty and practice some coding. Can you guess the output of the following snippet? </p>
<p><em>Note: Make sure you follow the comments in the given snippet which will unlock an important concept for you! </em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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))</pre>
<h2>Conclusion</h2>
<p>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.</p>
<p>Please <a href="https://blog.finxter.com/subscribe" target="_blank" rel="noreferrer noopener">subscribe </a>and <a href="https://blog.finxter.com" target="_blank" rel="noreferrer noopener">stay tuned </a>for more interesting articles!</p>
<h2 class="wp-block-block">Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>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?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>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.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-format-a-string-that-contains-curly-braces-in-python/" target="_blank" rel="noopener noreferrer">How To Format A String That Contains Curly Braces In Python?</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/09/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016