Home Python Python F-String Codes I Use Each Day

Python F-String Codes I Use Each Day

0
Python F-String Codes I Use Each Day

[ad_1]

A number of examples that can save the day most likely* 95% of time.

*I don’t have the precise information however severely, I guess you’ll discover these suggestions helpful most of the time!

Introduction

This text was initially posted on Medium.

I take advantage of f-strings each day. The irony is I additionally each day find yourself looking out the Internet to search out the right format to make use of. Till sooner or later I believed a greater use of my time could be to create a cheat sheet of the commonest formatting circumstances — AKA this text. It covers the next:

  • integers, floats, numbers and scientific notation
  • percentages %
  • dates
  • padding
  • including +/- sign up entrance of a quantity

It’s necessary to notice that the f-strings have been first launched in Python 3.6 (PEP 498 if you happen to REALLY should know) so be certain to examine the Python model first, if issues don’t be just right for you.

The format

Probably the most primary f-string format goes like this:

SmkAAj4o.jpg large

You should utilize this format to print numbers, texts, and even consider expressions.

creator = "pawjast"
12 months = 2022

print(f"Instance 1: {creator}") # string
print(f"Instance 2: {12 months}") # quantity
print(f"Instance 3: {2 + 2}") # expression

The output:

Instance 1: pawjast
Instance 2: 2022
Instance 3: 4

You might need observed that the 2+2 expression in Instance 3 received evaluated and 4 was printed.

You’ll get each, the title and the worth if you happen to add = signal to a variable.

textual content = "Knowledge Science Weblog"

print(f"{textual content=}")

The output:

textual content="Knowledge Science Weblog"

Template beneath generalizes how one can add a particular format to a variable:

t9JnTpBB.jpg large

Subsequent paragraphs exhibits examples of how one can use it.

Recap on numbers

Final cease earlier than going any additional. I’ll be utilizing other ways of writing numbers later within the article so let’s evaluate the commonest ones.

int_1 = 1
int_with_separator = 1_000  # `int` with 1,000 separator
float_1 = 1.125
float_2 = 3.50
scientific_1 = 1.23e2  # 1.23 * 10^2

print(f"Instance 1 - int: {int_1}")
print(f"Instance 2 - int with _ as 1000's separator: {int_with_separator}")
print(f"Instance 3 - float: {float_1}")
print(f"Instance 4 - float with trailing zero: {float_2}")
print(f"Instance 5 - float in scientific notation: {scientific_1}")

The output:

Instance 1 - int: 1
Instance 2 - int with _ as 1000's separator: 1000
Instance 3 - float: 1.125
Instance 4 - float with trailing zero: 3.5
Instance 5 - float in scientific notation: 123.0

You possibly can observe that:

  • floats had the trailing zeros truncated (Instance 4)
  • scientific notation was printed as a daily float
  • the remainder of the variables have been printed “as is”

Floats

The float kind is enforced by utilizing code f. What you need to management in floats is the variety of decimal locations.

pi_val = 3.141592

print(f"Instance 1: {pi_val:f}")
print(f"Instance 2: {pi_val:.0f}")
print(f"Instance 3: {pi_val:.1f}")
print(f"Instance 4: {pi_val:.3f}")

The output:

Instance 1: 3.141592
Instance 2: 3
Instance 3: 3.1
Instance 4: 3.142

💡 Aspect wordf-strings are versatile sufficient to permit nesting.

float_val = 1.5
precision = 3

print(f"{float_val:.{precision}f}")

The output:

1.500

Share

Use code % to implement share kind. Share remains to be a float so you possibly can nonetheless use .<whole_number> to manage the precision.

val = 0.5

print(f"Instance 1: {val:%}")
print(f"Instance 2: {val:.0%}")

The output:

Instance 1: 50.000000%
Instance 2: 50%

Extra examples of controlling precision in %:

val = 1.255

print(f"Instance 1: {val:.0%}")
print(f"Instance 2: {val:.1%}")

The output:

Instance 1: 125%
Instance 2: 125.5%

Scientific notation

If you need scientific notation to be printed as such (and never as a daily float) it may be enforced with e or E code.

val = 1.23e3  # 1.23 * 10^3

print(f"Instance 1: {val:e}")
print(f"Instance 2: {val:E}")

The output:

1: 1.230000e+03
2: 1.230000E+03

No shock the precision will be managed on this case too.

val = 1.2345e3

print(f"{val:.2e}")

The output:

1.23e+03

You possibly can even print a daily quantity in scientific notation.

val = 2022

print(f"{val:.3e}")

The output:

2.022e+03

Integers

Integers are enforced utilizing code d.

val = 1

print(f"{val:d}")

The output:

1

Including , to the code will print the 1000’s separator.

int_1 = 1000
int_2 = 1000_000_000

print(f"{int_1:,d}")
print(f"{int_2:,d}")

The output:

1,000
1,000,000,000

Numbers

If the intention is to only print a quantity, you should utilize generic code — n.

val_int = 1
val_float = 1.234
val_scient = 4.567e2

print(f"{val_int =: n}")
print(f"{val_float =: n}")
print(f"{val_scient =: n}")

The output:

val_int = 1
val_float = 1.234
val_scient = 456.7

You possibly can nonetheless use .<whole_number> format to manage the precision.

💡 Aspect word: on this case whole_number determines the complete variety of digits printed, not the variety of decimal factors! On high of that, n code will determine the most effective output format for a quantity.

val_float_1 = 1.234
val_float_2 = 20.234
val_float_3 = 123.456

print(f"{val_float_1 =: .2n}")  # prints as truncated float
print(f"{val_float_2 =: .2n}")  # prints as int
print(f"{val_float_3 =: .2n}")  # prints as scientific notation

The output:

val_float_1 = 1.2
val_float_2 = 20
val_float_3 = 1.2e+02

Dates

from datetime import date, datetime

Printing a date “as is” works precisely like printing every other variable.

day = date(
    12 months=2022,
    month=9,
    day=1
)

print(f"{day}")

The output:

2022-09-01

To recreate the format you’ll use the next codes:

  • %Y for 12 months
  • %m for month
  • %d for day

With these codes you possibly can e.g. create a brand new date format.

print(f"{day:%Y-%m-%d}")  # default look
print(f"{day:%Y/%m/%d}")  # use `/` as separator

The output:

2022-09-01
2022/09/01

It’s additionally potential to print a month as a textual content:

  • %b — brief model
  • %B — lengthy model
print(f"{day:%Y %b %d}")
print(f"{day:%Y %B %d}")

The output:

2022 Sep 01
2022 September 01

The identical variable will be printed a number of occasions.

print(f"{day:%b or %B}?")
print(f"{day:%Y %Y %Y}"

The output:

Sep or September?
2022 2022 2022

Reusing the identical variable will be helpful e.g. if you need to print the date and supply the day of the week as textual content (utilizing code %A ).

print(f"{day:%Y %b %d (%A)}")

The end result:

2022 Sep 01 (Thursday)

Final however not least, you possibly can swap %Y for %y to get brief model of the 12 months.

print(f"{day:%y.%m.%d}")

The output:

22.09.01

Datetime

Let’s specify two datetime variables.

day_and_time = datetime(
    12 months=2022,
    month=9,
    day=1,
    hour=17,
    minute=30,
    second=45
)
now = datetime.now()

print(f"{day_and_time}")
print(f"{now}")  # with mircoseconds

The output:

2022-09-01 17:30:45
2022-12-08 15:49:37.810347

Time format requires the next codes:

  • %H — hour
  • %M — minute
  • %S — second
  • %f — millisecond (1s = 1000 milliseconds)

Due to this fact, the default format would seem like beneath.

print(f"{now:%Y-%m-%d %H:%M:%S.%f}")

The end result:

2022-12-08 15:49:37.810347

f-string clearly creates a string (do that code to substantiate it: kind(f”now:%Y-%m-%d %H:%MpercentS.%f}”)). Due to this fact, if e.g. you aren’t proud of the variety of decimal factors for milliseconds, you possibly can simply truncate them.

print(f"{now:%Y-%m-%d %H:%M:%S.%f}"[:22])

The output:

2022-12-08 15:49:37.81

So as to change the 24hr format to 12hr format, you will have to:

  • swap hour code from %H to %I
  • Optionally add %p on the finish if you wish to add AM/PM to the time
print(f"24hr: {day_and_time:%Y-%m-%d %H:%M:%S}")
print(f"12hr: {day_and_time:%Y-%m-%d %I:%M:%S}")
print(f"12hr with AM/PM: {day_and_time:%Y-%m-%d %I:%M:%S %p}")

The output:

24hr: 2022-09-01 17:30:45
12hr: 2022-09-01 05:30:45
12hr with AM/PM: 2022-09-01 05:30:45 PM

Few extra helpful date codecs:

  • %j for day of the 12 months
  • %W for week of the 12 months (assuming Monday as first day of the week)
  • %U for week of the 12 months (assuming Sunday as first day of the week
day = date(
    12 months=2018,
    month=9,
    day=17
)

print(f"The date: {day}")
print(f"Day of the 12 months: {day: %j}")
print(f"Week of the 12 months (Mon): {day: %W}")
print(f"Week of the 12 months (Solar): {day: %U}")

The end result:

The date: 2018-09-17
Day of the 12 months:  260
Week of the 12 months (Mon):  38
Week of the 12 months (Solar):  37

Padding

Padding with empty areas.

val = 1

print(f"1: {val:1d}")
print(f"2: {val:second}")
print(f"3: {val:3d}")

The output:

1: 1
2:  1
3:   1

Padding with zeros.

val = 1

print(f"1: {val:01d}")
print(f"2: {val:02d}")
print(f"3: {val:03d}")

The output:

1: 1
2: 01
3: 001

I often use zero — padding with for loop to maintain the textual content properly aligned within the terminal.

for i in vary(11):
    print(f"{i:02d}")

The output:

01
02

...


09
10

Constructive/adverse signal

In some circumstances you’ll require to indicate a +/- signal subsequent to a quantity.

optimistic = 1.23
adverse = -1.23

print(f"1: {optimistic:+.2f}   {adverse:+.2f}")
print(f"2: {optimistic:-.2f}   {adverse:-.2f}")
print(f"3: {optimistic: .2f}   {adverse: .2f}")

The output:

1: +1.23   -1.23
2: 1.23   -1.23
3:  1.23   -1.23

Combining all issues collectively

# print variable with title, restrict precision and 1000's separator
val = 11500.23456

print(f"{val = :,.3f}")

The output:

val = 11,500.235

We’re achieved 🎉.

Full code

🔗 GitHub pocket book

Join with me

💬 Medium ◽ Twitter / X ◽ GitHub ◽ Substack ◽ LinkedIn

Sources

1️⃣ https://docs.python.org/3/reference/lexical_analysis.html#f-strings

2️⃣ https://docs.python.org/3/library/string.html#format-specification-mini-language

3️⃣ https://strftime.org/



[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here