How to use f-strings in Python | note.nkmk.me (2024)

Python 3.6 introduced a new feature, known as formatted string literals, or f-strings, to simplify the use of the string method format().

Contents

  • Basic usage of f-strings
  • Format specifications
    • Left-justify, center, right-justify
    • Zero-padding
    • Separator
    • Binary, octal, and hexadecimal representation
    • Decimal places and significant digits
    • Scientific notation
    • Percentage
    • Date and time (datetime)
  • Braces (curly brackets) {}
  • Nested replacement fields
  • Raw strings and f-strings
  • Difference between the format() method and f-strings
    • Expressions
    • How to specify dictionary keys
  • The = specifier in f-strings (Python 3.8 and later)

For a detailed overview of the string method format(), the built-in function format(), and format specification strings, refer to the following article.

  • Format strings and numbers with format() in Python

Basic usage of f-strings

The format() method inserts values into the replacement field {} using positional or keyword arguments.

a = 123b = 'abc'print('{} and {}'.format(a, b))# 123 and abcprint('{first} and {second}'.format(first=a, second=b))# 123 and abc

source: f_strings.py

An f-string is a string literal prefixed with f or F, like f'...' or F'...'. It allows you to specify variables directly in the replacement field {}.

print(f'{a} and {b}')# 123 and abcprint(F'{a} and {b}')# 123 and abc

source: f_strings.py

Like regular string literals, f-strings can use single quotes '', double quotes "", and triple quotes ''', """.

  • Create a string in Python (single/double/triple quotes, str())
print(f"{a} and {b}")# 123 and abcprint(f'''{a} and {b}''')# 123 and abcprint(f"""{a} and {b}""")# 123 and abc

source: f_strings.py

Format specifications

As with the format() method, f-strings can specify a variety of formats by adding a format specification string after the colon : in {}.

Some examples are shown here. For more information, refer to the following article.

  • Format strings and numbers with format() in Python

Left-justify, center, right-justify

s = 'abc'print(f'right : {s:*>8}')print(f'center: {s:*^8}')print(f'left : {s:*<8}')# right : *****abc# center: **abc***# left : abc*****

source: f_strings.py

Zero-padding

i = 1234print(f'zero padding: {i:08}')# zero padding: 00001234

source: f_strings.py

Separator

Binary, octal, and hexadecimal representation

i = 255print(f'bin : {i:b}')print(f'oct : {i:o}')print(f'hex(lower): {i:x}')print(f'hex(upper): {i:X}')# bin : 11111111# oct : 377# hex(lower): ff# hex(upper): FFprint(f'bin : {i:08b}')print(f'oct : {i:08o}')print(f'hex(lower): {i:08x}')print(f'hex(upper): {i:08X}')# bin : 11111111# oct : 00000377# hex(lower): 000000ff# hex(upper): 000000FFprint(f'bin : {i:#010b}')print(f'oct : {i:#010o}')print(f'hex(lower): {i:#010x}')print(f'hex(upper): {i:#010X}')# bin : 0b11111111# oct : 0o00000377# hex(lower): 0x000000ff# hex(upper): 0X000000FF

source: f_strings.py

Decimal places and significant digits

f = 12.3456print(f'decimal places : {f:.3f}')print(f'significant digits: {f:.3g}')# decimal places : 12.346# significant digits: 12.3

source: f_strings.py

Scientific notation

f = 12.3456print(f'exponent(lower): {f:.3e}')print(f'exponent(upper): {f:.3E}')# exponent(lower): 1.235e+01# exponent(upper): 1.235E+01

source: f_strings.py

Percentage

f = 0.123print(f'percent: {f:.2%}')# percent: 12.30%

source: f_strings.py

Date and time (datetime)

import datetimedt = datetime.datetime(2020, 1, 5, 20, 15, 30)print(f'datetime: {dt}')# datetime: 2020-01-05 20:15:30print(f'datetime: {dt:%A, %m/%d/%Y %I:%M:%S %p}')# datetime: Sunday, 01/05/2020 08:15:30 PMprint(f'datetime: {dt.isoformat()}')# datetime: 2020-01-05T20:15:30

source: f_strings.py

For more information on the datetime module, see the following article.

  • Handle date and time with the datetime module in Python

As in the last example, it is easier to use the isoformat() method than to specify format codes when converting to ISO 8601 format.

  • Convert between isoformat string and datetime in Python

Braces (curly brackets) {}

To include braces { and } in f-strings, double them like {{ and }}. Note that the backslash \ cannot be used.

n = 123print(f'{{}}-{n}-{{{n}}}')# {}-123-{123}

source: f_strings.py

Nested replacement fields

Similar to the format() method, f-strings allow replacement fields within other replacement fields. The number in the format specification string can be a variable.

n = 123i = 8print('{n:0{i}}'.format(n=n, i=i))# 00000123print(f'{n:0{i}}')# 00000123

You could also write:

f = 1.2345for i in range(5): print(f'{f:.{i}f}')# 1# 1.2# 1.23# 1.234# 1.2345

source: f_strings.py

Raw strings and f-strings

In regular strings, backslash \ represents special characters. However, when a string is prefixed with r or R, creating a raw string literal, backslash escapes are disregarded.

  • Raw strings in Python
print('x\ty')# x yprint(r'x\ty')# x\ty

source: f_strings.py

If you prefix a string with both r and f, it will be treated as both a raw string and an f-string. The order of r and f doesn't matter, and you can use either lowercase or uppercase letters.

x = 'XXX'y = 'YYY'print(f'{x}\t{y}')# XXX YYYprint(rf'{x}\t{y}')# XXX\tYYYprint(FR'{x}\t{y}')# XXX\tYYY

source: f_strings.py

Difference between the format() method and f-strings

Expressions

With the format() method, expressions cannot be included in the replacement field.

a = 3b = 4# print('{a} + {b} = {a + b}'.format(a=a, b=b))# KeyError: 'a + b'

source: f_strings.py

In contrast, f-strings allow the use of expressions within the replacement field. It is also possible to specify a format specification string for the outcome of the expression.

print(f'{a} + {b} = {a + b}')# 3 + 4 = 7print(f'{a} * {b} = {a * b}')# 3 * 4 = 12print(f'{a} / {b} = {a / b:.2e}')# 3 / 4 = 7.50e-01

source: f_strings.py

How to specify dictionary keys

When using a dictionary (dict) in a replacement field, the format() method does not require the key to be surrounded by ' or ".

d = {'key1': 10, 'key2': 20}print('{0[key1]}, {0[key2]}'.format(d))# 10, 20# print('{0["key1"]}, {0["key2"]}'.format(d))# KeyError: '"key1"'

source: f_strings.py

However, f-strings require the key to be enclosed in ' or ".

print(f'{d["key1"]}, {d["key2"]}')# 10, 20# print(f'{d[key1]}, {d[key2]}')# NameError: name 'key1' is not defined

source: f_strings.py

Like regular strings, you cannot use the same quotation marks within the string as the ones enclosing the entire string. For example, if the whole string is enclosed in ", use ' inside.

# print(f'{d['key1']}, {d['key2']}')# SyntaxError: invalid syntaxprint(f"{d['key1']}, {d['key2']}")# 10, 20

source: f_strings.py

Note that backslash escaping cannot be used within a replacement field.

# print(f'{d[\'key1\']}, {d[\'key2\']}')# SyntaxError: f-string expression part cannot include a backslash

source: f_strings.py

The = specifier in f-strings (Python 3.8 and later)

From Python 3.8, f-strings support an = specifier, which prints both variable names and their corresponding values.

i = 123print(f'{i=}')# i=123

source: f_strings.py

If you place a space before or after the variable name and =, it will be preserved in the output.

print(f'{i = }')# i = 123print(f'{ i = }')# i = 123

source: f_strings.py

You can also specify format specification strings and expressions with the = specifier.

print(f'{i = :#b}')# i = 0b1111011print(f'{i * 2 = }')# i * 2 = 246

source: f_strings.py

This also applies to lists and dictionaries.

l = [0, 10, 20]print(f'{l = }, {l[1] = }')# l = [0, 10, 20], l[1] = 10d = {'key1': 10, 'key2': 20}print(f'{d = }, {d["key1"] = }')# d = {'key1': 10, 'key2': 20}, d["key1"] = 10

source: f_strings.py

How to use f-strings in Python | note.nkmk.me (2024)

References

Top Articles
Blueberry Raspberry Pie Recipe | The Doughty Doughnut
Ark Prep 101 - Part 9: How Do I Use My Food Storage in My Everyday Recipes!
Whas Golf Card
Camera instructions (NEW)
Food King El Paso Ads
Brady Hughes Justified
Mrh Forum
America Cuevas Desnuda
Gunshots, panic and then fury - BBC correspondent's account of Trump shooting
Merlot Aero Crew Portal
270 West Michigan residents receive expert driver’s license restoration advice at last major Road to Restoration Clinic of the year
Progressbook Brunswick
Hello Alice Business Credit Card Limit Hard Pull
Shuiby aslam - ForeverMissed.com Online Memorials
Valentina Gonzalez Leak
Dexter Gomovies
Puretalkusa.com/Amac
Diamond Piers Menards
Craigslist Portland Oregon Motorcycles
Foxy Brown 2025
Hennens Chattanooga Dress Code
Craigslist List Albuquerque: Your Ultimate Guide to Buying, Selling, and Finding Everything - First Republic Craigslist
Concordia Apartment 34 Tarkov
18889183540
Culver's Flavor Of The Day Taylor Dr
Keci News
Exl8000 Generator Battery
Ou Football Brainiacs
Lcsc Skyward
Kristy Ann Spillane
Paradise Point Animal Hospital With Veterinarians On-The-Go
A Plus Nails Stewartville Mn
Missing 2023 Showtimes Near Mjr Southgate
Jambus - Definition, Beispiele, Merkmale, Wirkung
Six Flags Employee Pay Stubs
Cheap Motorcycles Craigslist
Ark Unlock All Skins Command
Pitco Foods San Leandro
Missouri State Highway Patrol Will Utilize Acadis to Improve Curriculum and Testing Management
Google Jobs Denver
4083519708
Terrier Hockey Blog
Nobodyhome.tv Reddit
Robeson County Mugshots 2022
“Los nuevos desafíos socioculturales” Identidad, Educación, Mujeres Científicas, Política y Sustentabilidad
Orion Nebula: Facts about Earth’s nearest stellar nursery
Bones And All Showtimes Near Johnstown Movieplex
Urban Blight Crossword Clue
Scarlet Maiden F95Zone
Tropical Smoothie Address
Kushfly Promo Code
Deviantart Rwby
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 5906

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.