Python F-strings: a Practical Guide to F-strings in Python (2024)

Summary: in this tutorial, you’ll learn about Python F-strings and how to use them to format strings and make your code more readable.

Introduction to the Python F-strings

Python 3.6 introduced the f-strings that allow you to format text strings faster and more elegant. The f-strings provide a way to embed variables and expressions inside a string literal using a clearer syntax than the format() method.

For example:

name = 'John's = f'Hello, {name}!'print(s)Code language: Python (python)

Output:

Hello, John!Code language: Python (python)

How it works.

  • First, define a variable with the value 'John'.
  • Then, place the name variable inside the curly braces {} in the literal string. Note that you need to prefix the string with the letter f to indicate that it is an f-string. It’s also valid if you use the letter in uppercase (F).
  • Third, print out the string s.

It’s important to note that Python evaluates the expressions in f-string at runtime. It replaces the expressions inside an f-string with their values.

Python f-string examples

The following example calls the upper() method to convert the name to uppercase inside the curly braces of an f-string:

name = 'John's = F'Hello, {name.upper()}!'print(s)Code language: Python (python)

Output:

Hello, JOHN!Code language: Python (python)

The following example uses multiple curly braces inside an f-string:

first_name = 'John'last_name = 'Doe's = F'Hello, {first_name} {last_name}!'print(s)Code language: Python (python)

Output:

Hello, John Doe!Code language: Python (python)

This example is equivalent to the above example but uses the join() method:

first_name = 'John'last_name = 'Doe's = F'Hello, {" ".join((first_name, last_name))}!'print(s)Code language: Python (python)

Output:

Hello, John Doe!Code language: Python (python)

Multiline f-strings

Python allows you to have multiline f-strings. To create a multiline f-string, you place the letter f in each line. For example:

name = 'John'website = 'PythonTutorial.net'message = ( f'Hello {name}. ' f"You're learning Python at {website}." )print(message)Code language: Python (python)

Output:

Hello John. You're learning Python on PythonTutorial.net.Code language: Python (python)

If you want to spread an f-string over multiple lines, you can use a backslash (\) to escape the return character like this:

name = 'John'website = 'PythonTutorial.net'message = f'Hello {name}. ' \ f"You're learning Python at {website}." print(message)Code language: Python (python)

The following example shows how to use triple quotes (""") with an f-string:

name = 'John'website = 'PythonTutorial.net'message = f"""Hello {name}.You're learning Python at {website}."""print(message)Code language: Python (python)

Output:

Hello John.You're learning Python at PythonTutorial.net.Code language: Python (python)

Curly braces

When evaluating an f-string, Python replaces double curly braces with a single curly brace. However, the doubled curly braces do not signify the start of an expression.

Python will not evaluate the expression inside the double curly brace and replace the double curly braces with a single one. For example:

s = f'{{1+2}}'print(s)Code language: Python (python)

Output:

{1+2}Code language: Python (python)

The following shows an f-string with triple curly braces:

s = f'{{{1+2}}}'print(s)Code language: Python (python)

Output:

{3}Code language: Python (python)

In this example, Python evaluates the {1+2} as an expression, which returns 3. Also, it replaces the remaining doubled curly braces with a single one.

To add more curly braces to the result string, you use more than triple curly braces:

s = f'{{{{1+2}}}}'print(s)Code language: Python (python)

Output:

{{1+2}}Code language: Python (python)

In this example, Python replaces each pair of doubled curly braces with a single curly brace.

The evaluation order of expressions in Python f-strings

Python evaluates the expressions in an f-string in the left-to-right order. This is obvious if the expressions have side effects like the following example:

def inc(numbers, value): numbers[0] += value return numbers[0]numbers = [0]s = f'{inc(numbers,1)},{inc(numbers,2)}'print(s)Code language: Python (python)

Output:

1,3Code language: Python (python)

In this example, the following function call increases the first number in the numbers list by one:

inc(numbers,1)Code language: Python (python)

After this call, the numbers[0] is one. And the second call increases the first number in the numbers list by 2, which results in 3.

Format numbers using f-strings

The following example use a f-string to format an integer as hexadecimal:

number = 16s = f'{number:x}'print(s) # 10Code language: PHP (php)

The following example uses the f-string to format a number as a scientific notation:

number = 0.01s = f'{number:e}'print(s) # 1.000000e-02Code language: PHP (php)

If you want to pad zeros at the beginning of the number, you use the f-string format as follows:

number = 200s = f'{number: 06}'print(s) # 00200Code language: PHP (php)

The 06 is the total number of the result numeric string including the leading zeros.

To specify the number of decimal places, you can also use the f-string:

number = 9.98567s = f'{number: .2f}'print(s) # 9.99Code language: PHP (php)

Note that the f-string also performs rounding in this case.

If the number is too large, you can use the number separator to make it easier to read:

number = 400000000000s = f'{number: ,}' # also can use _print(s) # 400,000,000,000Code language: PHP (php)

To format a number as a percentage, you use the following f-string format:

number = 0.1259s = f'{number: .2%}'print(s) # 12.59%s = f'{number: .1%}'print(s) # 12.5%Code language: PHP (php)

Python has more sophisticated format rules that you can reference via the following link.

Summary

  • Python f-strings provide an elegant way to format text strings.
  • Python replaces the result of an expression embedded inside the curly braces {} in an f-string at runtime.

Did you find this tutorial helpful ?

Python F-strings: a Practical Guide to F-strings in Python (2024)
Top Articles
Terrell Davis tours Broncos' stadium artist series | Salute to Broncos Country
Broncos GM George Paton explains why they kept three undrafted rookies on the roster
Skigebiet Portillo - Skiurlaub - Skifahren - Testberichte
Where To Go After Howling Pit Code Vein
How Much Does Dr Pol Charge To Deliver A Calf
The Daily News Leader from Staunton, Virginia
Fusion
Aiken County government, school officials promote penny tax in North Augusta
My Vidant Chart
[2024] How to watch Sound of Freedom on Hulu
7543460065
Operation Cleanup Schedule Fresno Ca
Used Sawmill For Sale - Craigslist Near Tennessee
Sonic Fan Games Hq
Hennens Chattanooga Dress Code
Kountry Pumpkin 29
Adt Residential Sales Representative Salary
Rufus Benton "Bent" Moulds Jr. Obituary 2024 - Webb & Stephens Funeral Homes
Military life insurance and survivor benefits | USAGov
Contracts for May 28, 2020
Bòlèt Florida Midi 30
Happy Homebodies Breakup
A Man Called Otto Showtimes Near Cinemark University Mall
Elite Dangerous How To Scan Nav Beacon
Idle Skilling Ascension
Watertown Ford Quick Lane
EVO Entertainment | Cinema. Bowling. Games.
Ascensionpress Com Login
Stickley Furniture
Meggen Nut
Noaa Marine Forecast Florida By Zone
Halsted Bus Tracker
Homewatch Caregivers Salary
Chicago Pd Rotten Tomatoes
Pokemmo Level Caps
Shaman's Path Puzzle
Goodwill Houston Select Stores Photos
Craigslist Car For Sale By Owner
The 38 Best Restaurants in Montreal
Domina Scarlett Ct
Otter Bustr
The TBM 930 Is Another Daher Masterpiece
Sam's Club Gas Prices Florence Sc
Bartow Qpublic
Puretalkusa.com/Amac
Xxn Abbreviation List 2023
Arcanis Secret Santa
Portal Pacjenta LUX MED
Csgold Uva
Whitney Wisconsin 2022
Market Place Tulsa Ok
Craigslist Com Brooklyn
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 5482

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.