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)

FAQs

How to use f-strings in Python | note.nkmk.me? ›

To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str. format(). F-strings provide a concise and convenient way to embed Python expressions inside string literals for formatting.

How do you use F in Python strings? ›

To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.

Should you use f strings in Python? ›

Using f-strings, your code will not only be cleaner but also faster to write. With f-strings you are not only able to format strings but also print identifiers along with a value (a feature that was introduced in Python 3.8).

How are F strings implemented in Python? ›

Also called formatted string literals, f-strings are string literals that have an f before the opening quotation mark. They can include Python expressions enclosed in curly braces. Python will replace those expressions with their resulting values. So, this behavior turns f-strings into a string interpolation tool.

What can I use instead of F-string in Python? ›

Python has several tools for string interpolation that support many formatting features. In modern Python, you'll use f-strings or the .format() method most of the time. However, you'll see the modulo operator ( % ) being used in legacy code.

How does F write work in Python? ›

The data to be written is stored in a list called data. The for statement is used to loop over each line of data in the list. The f.write(line + '\n') statement writes each line of data to the file with a newline character (\n) at the end. Finally, the file is automatically closed when the with block ends.

How do you quote an F-string in Python? ›

When using quotation marks inside an f-string, you can use either single quotes ('') or double quotes (“”). This allows you to include quotes within your strings without causing syntax errors.

Why are F strings faster? ›

F-strings are faster than str. format() because f-strings are evaluated at compile-time rather than at runtime. When you use an f-string, the expression inside the curly braces is evaluated at compile-time, and the resulting value is inserted into the string.

Why not use F-string in logging Python? ›

Using f-strings to format a logging message requires that Python eagerly format the string, even if the logging statement is never executed (e.g., if the log level is above the level of the logging statement), whereas using the extra keyword argument defers formatting until required.

How do you format numbers in F strings? ›

Formatting Numbers With F-Strings

F-strings can also be used to format numbers in various ways, including rounding, padding, and adding prefixes or suffixes. To format a number using F-strings, simply include the number inside the curly braces, followed by a colon and a format specifier.

How do you put an F-string on a new line in Python? ›

The \n characters tell Python to insert newline characters in the final string. Using parentheses, you can create multiline strings with f-strings without having to use triple quotes or escape characters. This can make your code more readable and concise.

How do you append F strings in Python? ›

The f-string was introduced in Python to make string formatting and interpolation easier. But you can also use it to append strings. To use the f-string, you simply write an f followed by quotation marks: f"" . You can then insert strings and variable names between the quotation marks.

What does F stand for in F-string Python? ›

Introduction. The release of Python version 3.6 introduced formatted string literals, simply called “f-strings.” They are called f-strings because you need to prefix a string with the letter 'f' to create an f- string. The letter 'f' also indicates that these strings are used for formatting.

When were f-strings added to Python? ›

Python f-strings or formatted strings are the new way to format strings. This feature was introduced in Python 3.6 under PEP-498.

Why do we use print f in Python? ›

A string prefixed with 'f' or 'F' and writing expressions as {expression} is a way to format string, which can include the value of Python expressions inside it. f-string in python lets you format data for printing using string templates.

How do you join strings with F in Python? ›

String Concatenation using f-string

If you are using Python 3.6+, you can use f-string for string concatenation too. It's a new way to format strings and introduced in PEP 498 - Literal String Interpolation. Python f-string is cleaner and easier to write when compared to format() function.

What is the meaning of .2f in Python? ›

In Python, the . 2f format specifier is used to format floating-point numbers as strings with two decimal places. This format specifier is part of the Python strings format syntax in Python.

What does F mean in a string? ›

F Strings are just a shorthand for str. format - and while they are convinient, they can't do a lot of things that str. format can. For example, with str. format , you can fetch the format string from somewhere (maybe user input / config) and then format your input using that format string.

How do you use an apostrophe in an F-string in Python? ›

Another way to create a string with an apostrophe is to use the escape character backslash \ before the apostrophe itself. # Create a string with an apostrophe using the backslash \. I enjoyed last night's concert.

Top Articles
Little League Coach Daily Themed Crossword
Riverrun Rv Park Middletown Photos
Craigslist Warren Michigan Free Stuff
Garrison Blacksmith Bench
Holly Ranch Aussie Farm
Bluegabe Girlfriend
Here's how eating according to your blood type could help you keep healthy
Atrium Shift Select
Visustella Battle Core
Find your energy supplier
OSRS Dryness Calculator - GEGCalculators
Think Up Elar Level 5 Answer Key Pdf
Magic Mike's Last Dance Showtimes Near Marcus Cedar Creek Cinema
Stihl Km 131 R Parts Diagram
272482061
623-250-6295
Hyvee Workday
Rqi.1Stop
SuperPay.Me Review 2023 | Legitimate and user-friendly
Aol News Weather Entertainment Local Lifestyle
Reviews over Supersaver - Opiness - Spreekt uit ervaring
Chamberlain College of Nursing | Tuition & Acceptance Rates 2024
Restored Republic June 16 2023
Manuela Qm Only
Albert Einstein Sdn 2023
Inter Miami Vs Fc Dallas Total Sportek
Summoners War Update Notes
manhattan cars & trucks - by owner - craigslist
Downloahub
Mercedes W204 Belt Diagram
RFK Jr., in Glendale, says he's under investigation for 'collecting a whale specimen'
Microsoftlicentiespecialist.nl - Microcenter - ICT voor het MKB
Mta Bus Forums
Vivek Flowers Chantilly
Geology - Grand Canyon National Park (U.S. National Park Service)
Elizaveta Viktorovna Bout
Dollar Tree's 1,000 store closure tells the perils of poor acquisitions
Search All of Craigslist: A Comprehensive Guide - First Republic Craigslist
Mid America Clinical Labs Appointments
Tripadvisor Vancouver Restaurants
Former Employees
Saline Inmate Roster
Patricia And Aaron Toro
Elven Steel Ore Sun Haven
Random Animal Hybrid Generator Wheel
Stitch And Angel Tattoo Black And White
Hello – Cornerstone Chapel
Race Deepwoken
The Jazz Scene: Queen Clarinet: Interview with Doreen Ketchens – International Clarinet Association
Wrentham Outlets Hours Sunday
Vrca File Converter
Mazda 3 Depreciation
Latest Posts
Article information

Author: Jonah Leffler

Last Updated:

Views: 5275

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.