avatarYang Zhou

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2740

Abstract

aries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors.</p><h1 id="c8f3">1. Using the Built-in Format Function</h1><p id="769a">Since Python 3, every Python string has a built-in function named <code>format()</code> to do formatting stuff.</p><p id="c474">Let’s use this function to rewrite the previous examples:</p><div id="98ae"><pre><span class="hljs-attribute">name</span>=<span class="hljs-string">'Yang'</span> <span class="hljs-built_in">print</span>(<span class="hljs-string">"Hi, {}"</span>.format(name)) <span class="hljs-comment"># Hi, Yang</span></pre></div><p id="8129">And for printing the number:</p><div id="0195"><pre><span class="hljs-attribute">protocol</span>=7 <span class="hljs-built_in">print</span>(<span class="hljs-string">"Hi, {:03}"</span>.format(protocol)) <span class="hljs-comment"># Hi, 007</span></pre></div><p id="d62f">This syntax brought some new tricks. Such as the usages of placeholders:</p><div id="f971"><pre><span class="hljs-attribute">name</span>=<span class="hljs-string">'Yang'</span> <span class="hljs-attribute">desc</span>=<span class="hljs-string">'amazing'</span> <span class="hljs-built_in">print</span>(<span class="hljs-string">"Hi, {n}! You are {d}!"</span>.format(<span class="hljs-attribute">n</span>=name,d=desc)) <span class="hljs-comment"># Hi, Yang! You are amazing!</span></pre></div><h1 id="4ec7">2. Formatted String Literals: the F-Strings</h1><p id="b13e">The <code>format()</code> function is much better, but still not elegant enough.</p><p id="996e">But since Python 3.6, the appearance of the f-strings made the string formatting really Pythonic.</p><p id="127f">What does Pythonic mean?</p><p id="0b15">It means shorter, cleaner, neater, and better.</p><p id="5670">Let’s rewrite the same example again:</p><div id="644d"><pre><span class="hljs-attribute">name</span>=<span class="hljs-string">'Yang'</span> <span class="hljs-attribute">desc</span>=<span class="hljs-string">'amazing'</span> <span class="hljs-built_in">print</span>(f<span class="hljs-string">"Hi, {name}! You are {desc}!"</span>) <span class="hljs-comment"># Hi, Yang! You are amazing!</span></pre></div><p id="4a3b">Or print a specific number:</p><div id="bd56"><pre><span class="hljs-attribute">name</span>=<span class="hljs-string">'Yang'</span> <span class="hljs-attribute">protocol</span>=7 <span class="hljs-built_in">print</span>(f<span class="hljs-string">"Hi, {name}! You are {protocol:03d}!"</span>) <span class="hljs-comment"># Hi, Yang! You are 007!</span></pre></div><p id="a23f">Or even run a function inside your string! 😎</p> <figure id="6a30"> <div> <div>

Options

            <iframe class="gist-iframe" src="/gist/ZhouYang1993/80887eb512176216318d0f8f192c57b8.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="7248">Far from enough yet, there are more amazing tricks of f-strings in Python:</p><div id="34d3" class="link-block">
      <a href="https://python.plainenglish.io/7-levels-of-using-f-strings-in-python-99b11707d14b">
        <div>
          <div>
            <h2>7 Levels of Using F-Strings in Python</h2>
            <div><h3>Dive into the string formatting technique in Python</h3></div>
            <div><p>python.plainenglish.io</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*c10P4_UA9cW3iRk9)"></div>
          </div>
        </div>
      </a>
    </div><h1 id="4151">3. Template Strings: An Unpopular Way</h1><p id="4cd4">Last but not least, there is a not very common technique for string formatting in Python: the template string.</p><p id="2d7c">Simply put, as mentioned in the official Python document, it’s just another simple syntax for string formatting.</p><blockquote id="6c98"><p>A primary use case for template strings is for internationalization, since in that context, the simpler syntax and functionality makes it easier to translate than other built-in string formatting facilities in Python. (from the <a href="https://docs.python.org/3/library/string.html?highlight=string%20format#template-strings">Python document</a>)</p></blockquote><p id="17d9">For instance, let’s use this approach to print the same results as a previous example:</p><div id="c98d"><pre><span class="hljs-keyword">from</span> string import Template

t = Template(<span class="hljs-string">'Hi, $name!'</span>) <span class="hljs-built_in">print</span>(t.substitute(<span class="hljs-attribute">name</span>=<span class="hljs-string">"Yang"</span>)) <span class="hljs-comment"># Hi, Yang!</span></pre></div><p id="07e9">Personally, I never used this syntax since the f-strings can satisfy all my daily requirements already.</p><h1 id="a9eb">Conclusion</h1><p id="aa1c">No programming language was great on the first day it was born. Python is my favourite language because it keeps evolving all the time. I believe it will become more and more elegant. 🙂</p><p id="0a34"><b><i>Thanks for reading. If you like it, please <a href="https://yangzhou1993.medium.com/follow">follow</a> or <a href="https://yangzhou1993.medium.com/membership">support</a> me</i></b> <b><i>to enjoy more great articles. </i></b>🙂</p></article></body>

4 String Formatting Techniques in Python — Feel the Evolution

See the big picture and find your favourite one

Photo by Gabriel Gusmao on Unsplash

Python is a rapidly evolving language.

In the old days (Python 2.x), its string formatting syntax brought the idea from the C language. You have to use the “%” operator, whose syntax is not elegant enough and may cause ugly code, for string formatting.

Since Python 3.x, a new built-in method called format() was introduced and made things neater.

From Python 3.6, the birth of formatted string literals, so-called f-strings, made a great stir in the Python community.

This article will summarise the 4 common ways for string formatting in Python. After reading, you can see the big picture, feel the evolution of Python, and most importantly, find the right way for your programs.

0. C Style String Formatting with the “%” Operator

If you started to use Python since its 2.x version, you definitely know this printf-style string formatting syntax. It’s kind of old-school but still available for the latest Python version.

For example, the following code print a string including another string variable:

name='Yang'
print("Hi, %s" %name)
# Hi, Yang

Or print a formatted number:

protocol=7
print("Hi, %03d" %protocol)
# Hi, 007

There are more complicated usages for this method. But the problem is that you probably need to save the official reference to your bookmarks. Cause it’s too hard to remember all syntax details.

In addition, even the official document said that using newer formatting ways may avoid some unexpected errors:

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors.

1. Using the Built-in Format Function

Since Python 3, every Python string has a built-in function named format() to do formatting stuff.

Let’s use this function to rewrite the previous examples:

name='Yang'
print("Hi, {}".format(name))
# Hi, Yang

And for printing the number:

protocol=7
print("Hi, {:03}".format(protocol))
# Hi, 007

This syntax brought some new tricks. Such as the usages of placeholders:

name='Yang'
desc='amazing'
print("Hi, {n}! You are {d}!".format(n=name,d=desc))
# Hi, Yang! You are amazing!

2. Formatted String Literals: the F-Strings

The format() function is much better, but still not elegant enough.

But since Python 3.6, the appearance of the f-strings made the string formatting really Pythonic.

What does Pythonic mean?

It means shorter, cleaner, neater, and better.

Let’s rewrite the same example again:

name='Yang'
desc='amazing'
print(f"Hi, {name}! You are {desc}!")
# Hi, Yang! You are amazing!

Or print a specific number:

name='Yang'
protocol=7
print(f"Hi, {name}! You are {protocol:03d}!")
# Hi, Yang! You are 007!

Or even run a function inside your string! 😎

Far from enough yet, there are more amazing tricks of f-strings in Python:

3. Template Strings: An Unpopular Way

Last but not least, there is a not very common technique for string formatting in Python: the template string.

Simply put, as mentioned in the official Python document, it’s just another simple syntax for string formatting.

A primary use case for template strings is for internationalization, since in that context, the simpler syntax and functionality makes it easier to translate than other built-in string formatting facilities in Python. (from the Python document)

For instance, let’s use this approach to print the same results as a previous example:

from string import Template
t = Template('Hi, $name!')
print(t.substitute(name="Yang"))
# Hi, Yang!

Personally, I never used this syntax since the f-strings can satisfy all my daily requirements already.

Conclusion

No programming language was great on the first day it was born. Python is my favourite language because it keeps evolving all the time. I believe it will become more and more elegant. 🙂

Thanks for reading. If you like it, please follow or support me to enjoy more great articles. 🙂

Python
Programming
Technology
Software Development
Data Science
Recommended from ReadMedium