avatarBex T.

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

6206

Abstract

t">{disco:+}</span>, Negative number: <span class="hljs-subst">{fever:+}</span>"</span>)</pre></div><div id="4cc8"><pre><span class="hljs-attr">Positive number:</span> <span class="hljs-string">+10,</span> <span class="hljs-attr">Negative number:</span> <span class="hljs-number">-12</span></pre></div><p id="6a18"><b>3. Thousands separator: <code>{:,}</code></b></p><p id="9abf">A person can count up to a million out loud but will have trouble counting the six 0s in a million without a thousands separator.</p><p id="f103">When you are dealing with large numbers, always put a comma for every third digit for everybody's sake, using the <code>{: ,}</code> format code.</p><div id="e89a"><pre>fuzzy_logic = <span class="hljs-number">1000000</span>

<span class="hljs-built_in">print</span>(<span class="hljs-string">f"A million: <span class="hljs-subst">{fuzzy_logic:,}</span>"</span>) <span class="hljs-built_in">print</span>(<span class="hljs-string">f"A trillion: <span class="hljs-subst">{fuzzy_logic ** <span class="hljs-number">2</span>:,}</span>"</span>)</pre></div><div id="4e8c"><pre><span class="hljs-selector-tag">A</span> <span class="hljs-selector-tag">million</span>: <span class="hljs-number">1</span>,<span class="hljs-number">000</span>,<span class="hljs-number">000</span> <span class="hljs-selector-tag">A</span> <span class="hljs-selector-tag">trillion</span>: <span class="hljs-number">1</span>,<span class="hljs-number">000</span>,<span class="hljs-number">000</span>,<span class="hljs-number">000</span>,<span class="hljs-number">000</span></pre></div><p id="0c55"><b>4. Percentage formatting: <code>{:.n%}</code></b></p><p id="11a0">I prefer decimals to represent proportions. But for some strange reason, I heard some people like to put this weird sign, %, and multiply the proportion by 100.</p><p id="13e9">To save them the trouble of multiplying, I suggest them using the <code>.n%</code> format specifier:</p><div id="00ce"><pre>jumbo_shrimp = <span class="hljs-number">0.4245</span>

<span class="hljs-built_in">print</span>(<span class="hljs-string">f"42% of something: <span class="hljs-subst">{jumbo_shrimp:<span class="hljs-number">.0</span>%}</span>"</span>) <span class="hljs-built_in">print</span>(<span class="hljs-string">f"Percentage of something: <span class="hljs-subst">{jumbo_shrimp:<span class="hljs-number">.1</span>%}</span>"</span>) <span class="hljs-built_in">print</span>(<span class="hljs-string">f"Percentage of another thing: <span class="hljs-subst">{jumbo_shrimp:<span class="hljs-number">.2</span>%}</span>"</span>)</pre></div><div id="91b7"><pre><span class="hljs-number">42</span><span class="hljs-string">%</span> <span class="hljs-attr">of something:</span> <span class="hljs-number">42</span><span class="hljs-string">%</span> <span class="hljs-attr">Percentage of something:</span> <span class="hljs-number">42.4</span><span class="hljs-string">%</span> <span class="hljs-attr">Percentage of another thing:</span> <span class="hljs-number">42.45</span><span class="hljs-string">%</span></pre></div><p id="3df4"><b>5. Scientific notation: <code>{:.ne}</code></b></p><p id="57f9">Now, this one always confuses me.</p><p id="871b">Why truncate beautifully large and small numbers with all their 100-digit glory with scientific notation? They should be left as-is and read the way they were intended: from the beginning to the end, horizontally scrolling the mouse, forgetting which digit you are at, and starting from the beginning a dozen times.</p><p id="dbc9">But engineers, physicists, and chemists don't do that, which is probably why the <code>{:.ne}</code> format code exists in Python.</p><div id="a2d7"><pre>ninja_turtles = <span class="hljs-number">123456789</span>

<span class="hljs-built_in">print</span>(<span class="hljs-string">f"Scientific notation: <span class="hljs-subst">{ninja_turtles:<span class="hljs-number">.1</span>e}</span>"</span>) <span class="hljs-built_in">print</span>(<span class="hljs-string">f"Scientific notation: <span class="hljs-subst">{ninja_turtles:<span class="hljs-number">.2</span>e}</span>"</span>)</pre></div><div id="d10d"><pre><span class="hljs-attr">Scientific notation:</span> <span class="hljs-number">1.2e+08</span> <span class="hljs-attr">Scientific notation:</span> <span class="hljs-number">1.23e+08</span></pre></div><p id="3dc3"><b>6. Printing the value of a variable: <code>{=}</code></b></p><p id="a806">Sometimes, I want to print both the variable name and its value. Instead of doing it the classic way like my ancestors with <code>f"variable = {variable}"</code>, I choose the shorter version with <code>{variable=}</code>:</p><div id="2b97"><pre>sassy = <span class="hljs-number">1</span> pants = <span class="hljs-number">0</span>

<span class="hljs-built_in">print</span>(<span class="hljs-string">f"<span class="hljs-subst">{sassy=}</span>"</span>) <span class="hljs-built_in">print</span>(<span class="hljs-string">f"<span class="hljs-subst">{pants = }</span>"</span>)</pre></div><div id="9f4e"><pre><span class="hljs-attr">sassy</span>=<span class="hljs-number">1</span> <span class="hljs-attr">pants</span> = <span class="hljs-number">0</span></pre></div><p id="9646">I am weird like that.</p><p id="62c1"><b>7. Pad zeros for integers : <code>{:nd}</code></b></p><p id="4db2">Here is how you can buff up extremely small integers with padding of 0s using the <code>{:0nd}</code> format code:</p><div id="20f0"><pre>kangaroo_pouch = <span class="hljs-number">42</span>

<span class="hljs-built_in">print</span>(<span class="hljs-string">f"<span class="hljs-subst">{kangaroo_pouch:01d}</span>"</span>) <span class="hljs-built_in">print</span>(<span class="hljs-string">f"<span class="hljs-subst">{kangaroo_pouch:02d}</span>"</span>) <span class="hljs-comment"># Reached the string length of two</span> <span class="hljs-built_in">print</span>(<span class="hljs-string">f"<span class="hljs-subst">{kangaroo_pouch:03d}</span>"</span>) <span class="hljs-comment"># Now the 0s will show</span> <span class="hljs-built_in">print</span>(<span class="hljs-string">f"<span class="hljs-subst">{kangaroo_pouch:04d}</span>"</span>)</pre></div><div id="f61b"><pre><span class="hljs-number">

Options

42</span> <span class="hljs-number">42</span> <span class="hljs-number">042</span> <span class="hljs-number">0042</span></pre></div><p id="d97f">Just remember to change <code>n</code> to control the number of digits for those special occasions when you need all your integers to have the same format and length.</p><p id="78fe"><b>8. Mixing</b></p><p id="6b96">With great power comes great responsibility. We should often read this quote to people who know how to mix f-string format codes, to keep them in check.</p><p id="eb6d">Because if we don't, they will write these unbearably unreadable but unfortunately, a functional combination of format codes (read this sentence a few times out loud for fun):</p><div id="fa97"><pre>taco_tuesday = <span class="hljs-number">1240000.1235</span>

<span class="hljs-built_in">print</span>(<span class="hljs-string">f"<span class="hljs-subst">{taco_tuesday = :+,<span class="hljs-number">.3</span>f}</span>"</span>)</pre></div><div id="a90b"><pre><span class="hljs-attr">taco_tuesday</span> = +<span class="hljs-number">1</span>,<span class="hljs-number">240</span>,<span class="hljs-number">000.123</span></pre></div><div id="3fcc"><pre><span class="hljs-built_in">print</span>(<span class="hljs-string">f"<span class="hljs-subst">{taco_tuesday = : >+<span class="hljs-number">30</span>,<span class="hljs-number">.6</span>f}</span>!"</span>)</pre></div><div id="7963"><pre><span class="hljs-attr">taco_tuesday</span> = +<span class="hljs-number">1</span>,<span class="hljs-number">240</span>,<span class="hljs-number">000.123500</span>!</pre></div><p id="4fa6">The above are just pure insults to <a href="https://peps.python.org/pep-0020/">the Zen of Python</a>, which states that "Readability counts".</p><p id="6d03"><b>9. Pretty printing dates</b></p><p id="b810">I think the future generations will sincerely "praise" us for coming up with the effing many brilliant ways of representing date and time.</p><p id="f8ff">We can do it with the year first, then the month and day. Or, we hate monotony, so let's change it up to month, day, and a two-digit year.</p><p id="2215">And don't even get us started on telling the time. There are 12-hour, 24-hour, military (that one is fun), <a href="https://www.hko.gov.hk/en/education/astronomy-and-time/time-service/00409-astronomical-time-and-atomic-time.html#:~:text=Astronomical%20Time%20is%20based%20on,Earth%20revolving%20around%20the%20Sun.">astronomical</a>, solar, atomic, timestamp, 24 timezones, and what did I forget? Ooh, yes — the <a href="https://reciprocity.com/resources/types-of-iso-standards/#:~:text=As%20mentioned%2C%20there%20are%20roughly,standards%20for%20specific%20industries%2C%20too.">22 thousand, totally unconfusing ISO formats</a>.</p><p id="542e">Whichever format you choose, you can print the date and time using the codes from above or special datetime literal strings:</p><div id="9fe5"><pre>import datetime

now = datetime.datetime.now()

<span class="hljs-keyword">print</span>(f<span class="hljs-string">"Today is {now:%A, %B %d, %Y}. The time is {now:%I:%M %p}."</span>)</pre></div><div id="a301"><pre>Today <span class="hljs-keyword">is</span> Monday, March <span class="hljs-number">13</span>, <span class="hljs-number">2023.</span> The time <span class="hljs-keyword">is</span> <span class="hljs-number">09</span>:<span class="hljs-number">17</span> AM.</pre></div><p id="ecb7">Here are the 15 most common:</p><ol><li><code>%Y</code> - 4-digit year</li><li><code>%y</code> - 2-digit year</li><li><code>%m</code> - 2-digit month (01-12)</li><li><code>%b</code> - Month abbreviation (Jan-Dec)</li><li><code>%B</code> - Full month name (January-December)</li><li><code>%d</code> - Day of the month (01-31)</li><li><code>%a</code> - Weekday abbreviation (Mon-Sun)</li><li><code>%A</code> - Full weekday name (Monday-Sunday)</li><li><code>%w</code> - Weekday as a decimal number (0-6, where 0 is Sunday)</li><li><code>%H</code> - Hour in 24-hour format (00-23)</li><li><code>%I</code> - Hour in 12-hour format (01-12)</li><li><code>%p</code> - AM/PM designation</li><li><code>%M</code> - Minute (00-59)</li><li><code>%S</code> - Second (00-59)</li><li><code>%f</code> - Microsecond (000000-999999)</li></ol><p id="499b">You can mix them up with any punctuation you want inside the braces and go nuts!</p><p id="ffef">Thank you for sticking to the end. As a bonus, I will leave you with another time format — <a href="https://en.wikipedia.org/wiki/Decimal_time">decimal time</a>.</p><p id="e2c7">During the French Revolution, kind French people wanted to decimalize all measures of time and distance, and they divided the day into 10 hours, each hour containing 100 minutes and each minute with 100 seconds.</p><p id="ca3f">But alas, they couldn't convince the tiny 1 billion population of the 18th century to change all the clocks and watches in the world.</p><div id="27bb" class="link-block"> <a href="https://ibexorigin.medium.com/membership"> <div> <div> <h2>Join Medium with my referral link - Bex T.</h2> <div><h3>Get exclusive access to all my ⚡premium⚡ content and all over Medium without limits. Support my work by buying me a…</h3></div> <div><p>ibexorigin.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*6YF5V29YflsUcRPR)"></div> </div> </div> </a> </div><div id="cd4a" class="link-block"> <a href="https://ibexorigin.medium.com/subscribe"> <div> <div> <h2>Get an email whenever Bex T. publishes.</h2> <div><h3>Get an email whenever Bex T. publishes. By signing up, you will create a Medium account if you don't already have one…</h3></div> <div><p>ibexorigin.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*4l-QWzlLVHyLmkSw)"></div> </div> </div> </a> </div></article></body>

Have Mercy on Yourself And Learn These 9 Everyday Python f-string Codes

The ‘eff’ in f-strings may as well stand for… (not that! What a twisted mind you have) for ‘freaking awesome’!

Photo by drmakete lab

If you clicked on this article, you've probably already used f-strings in Python. You know that you can throw almost any expression between braces to sprinkle dynamic values into strings.

But, from time to time, you see a guy using something like print(f"{f'${number:.3f}':>10s}") (probably to show off) and you undoubtedly say what the f...-string is that?!

By the end of this post, you will find the answer to that question and acquire the skills to write even more messed up but very useful f-string codes that take your string manipulation skills to a whole new level (and make others wonder if you are just showing off, too).

Basics of format codes

Format codes in f-strings start with an expression inside braces:

from datetime import date

print(f"Today is {date.today()}")
print(f"This is result from a lambda: {(lambda x: x ** 2)(3)}")
Today is 2023-03-13
This is result from a lambda: 9

The expression is evaluated and the internal string representation of the result is embedded into the f-string. But before the embedding part happens, you can do all sorts of interesting stuff to the result without leaving the comfort of the double quotation marks.

And all through format codes.

0. Float precision — {:.nf}

Let's start with the most used one — float precision. From now on, don't let anyone catch you using the round function to round them long floats. Use the .nf code, replacing the n with the precision you want:

cheese_puffs = 3.14159265359

print(f"The value of pi is approximately {cheese_puffs:.4f}")
The value of pi is approximately 3.1416

1. Left/right/center align — {:(<>^)n}

Many libraries or functions use special formatting to make walls of text easier on the eye. This requires careful control of the length of each line of text, but it can get tricky when dynamic values in f-strings get involved.

But you can align the text inside the braces within a specified length:

banana = 42

print(f"The answer is {banana:<10}!")
The answer is 42        !

For example, :<10 assigns the space between braces a length of 10 characters and, after left-aligning banana's value, fills the rest of the length with spaces.

You can use > and ^ to right and center-align numbers, respectively (works on strings as well):

hammock = 42

print(f"The answer is {hammock:>10}!")
The answer is         42!
bubble_wrap = 42

print(f"The answer is {bubble_wrap:^10}!")
The answer is     42    !

To fill the leftover space with another character, like an underscore, put it before the alignment symbol:

bubble_wrap = 42

print(f"The answer is {bubble_wrap:_^10}!")
The answer is ____42____!

2. Sign indicator: {:+}

There are many cases where you work with values with different meanings based on their sign, like financial data or temperature readings. In these situations, you can use the {:+} format code to display the sign of the number regardless of its value:

disco = 10
fever = -12

print(f"Positive number: {disco:+}, Negative number: {fever:+}")
Positive number: +10, Negative number: -12

3. Thousands separator: {:,}

A person can count up to a million out loud but will have trouble counting the six 0s in a million without a thousands separator.

When you are dealing with large numbers, always put a comma for every third digit for everybody's sake, using the {: ,} format code.

fuzzy_logic = 1000000

print(f"A million: {fuzzy_logic:,}")
print(f"A trillion: {fuzzy_logic ** 2:,}")
A million: 1,000,000
A trillion: 1,000,000,000,000

4. Percentage formatting: {:.n%}

I prefer decimals to represent proportions. But for some strange reason, I heard some people like to put this weird sign, %, and multiply the proportion by 100.

To save them the trouble of multiplying, I suggest them using the .n% format specifier:

jumbo_shrimp = 0.4245

print(f"42% of something: {jumbo_shrimp:.0%}")
print(f"Percentage of something: {jumbo_shrimp:.1%}")
print(f"Percentage of another thing: {jumbo_shrimp:.2%}")
42% of something: 42%
Percentage of something: 42.4%
Percentage of another thing: 42.45%

5. Scientific notation: {:.ne}

Now, this one always confuses me.

Why truncate beautifully large and small numbers with all their 100-digit glory with scientific notation? They should be left as-is and read the way they were intended: from the beginning to the end, horizontally scrolling the mouse, forgetting which digit you are at, and starting from the beginning a dozen times.

But engineers, physicists, and chemists don't do that, which is probably why the {:.ne} format code exists in Python.

ninja_turtles = 123456789

print(f"Scientific notation: {ninja_turtles:.1e}")
print(f"Scientific notation: {ninja_turtles:.2e}")
Scientific notation: 1.2e+08
Scientific notation: 1.23e+08

6. Printing the value of a variable: {=}

Sometimes, I want to print both the variable name and its value. Instead of doing it the classic way like my ancestors with f"variable = {variable}", I choose the shorter version with {variable=}:

sassy = 1
pants = 0

print(f"{sassy=}")
print(f"{pants = }")
sassy=1
pants = 0

I am weird like that.

7. Pad zeros for integers : {:nd}

Here is how you can buff up extremely small integers with padding of 0s using the {:0nd} format code:

kangaroo_pouch = 42

print(f"{kangaroo_pouch:01d}")
print(f"{kangaroo_pouch:02d}") # Reached the string length of two
print(f"{kangaroo_pouch:03d}") # Now the 0s will show
print(f"{kangaroo_pouch:04d}")
42
42
042
0042

Just remember to change n to control the number of digits for those special occasions when you need all your integers to have the same format and length.

8. Mixing

With great power comes great responsibility. We should often read this quote to people who know how to mix f-string format codes, to keep them in check.

Because if we don't, they will write these unbearably unreadable but unfortunately, a functional combination of format codes (read this sentence a few times out loud for fun):

taco_tuesday = 1240000.1235

print(f"{taco_tuesday = :+,.3f}")
taco_tuesday = +1,240,000.123
print(f"{taco_tuesday = : >+30,.6f}!")
taco_tuesday =              +1,240,000.123500!

The above are just pure insults to the Zen of Python, which states that "Readability counts".

9. Pretty printing dates

I think the future generations will sincerely "praise" us for coming up with the effing many brilliant ways of representing date and time.

We can do it with the year first, then the month and day. Or, we hate monotony, so let's change it up to month, day, and a two-digit year.

And don't even get us started on telling the time. There are 12-hour, 24-hour, military (that one is fun), astronomical, solar, atomic, timestamp, 24 timezones, and what did I forget? Ooh, yes — the 22 thousand, totally unconfusing ISO formats.

Whichever format you choose, you can print the date and time using the codes from above or special datetime literal strings:

import datetime

now = datetime.datetime.now()

print(f"Today is {now:%A, %B %d, %Y}. The time is {now:%I:%M %p}.")
Today is Monday, March 13, 2023. The time is 09:17 AM.

Here are the 15 most common:

  1. %Y - 4-digit year
  2. %y - 2-digit year
  3. %m - 2-digit month (01-12)
  4. %b - Month abbreviation (Jan-Dec)
  5. %B - Full month name (January-December)
  6. %d - Day of the month (01-31)
  7. %a - Weekday abbreviation (Mon-Sun)
  8. %A - Full weekday name (Monday-Sunday)
  9. %w - Weekday as a decimal number (0-6, where 0 is Sunday)
  10. %H - Hour in 24-hour format (00-23)
  11. %I - Hour in 12-hour format (01-12)
  12. %p - AM/PM designation
  13. %M - Minute (00-59)
  14. %S - Second (00-59)
  15. %f - Microsecond (000000-999999)

You can mix them up with any punctuation you want inside the braces and go nuts!

Thank you for sticking to the end. As a bonus, I will leave you with another time format — decimal time.

During the French Revolution, kind French people wanted to decimalize all measures of time and distance, and they divided the day into 10 hours, each hour containing 100 minutes and each minute with 100 seconds.

But alas, they couldn't convince the tiny 1 billion population of the 18th century to change all the clocks and watches in the world.

Python
Programming
Data Science
Machine Learning
Software Development
Recommended from ReadMedium