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)

FAQs

Python F-strings: a Practical Guide to F-strings in Python? ›

f-strings (formatted string literals) are a way to embed expressions inside string literals in Python, using curly braces {}. They provide an easy and readable way to format strings dynamically. sentence = f"My name is {name} and I am {age} years old."

How do you do F-strings in Python? ›

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.

What is the difference between F and F string in Python? ›

In source code, f-strings are string literals that are prefixed by the letter 'f' or 'F'. Everywhere this PEP uses 'f', 'F' may also be used. There is no difference at all. See the definition of Formatted string literals in the Python documentation.

Why put f before string Python? ›

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.

What is the alternative to F string in Python? ›

Alternative Formatting Methods. While Python's f-string formatting is a powerful and efficient tool, it's not the only way to format strings in Python. Two other popular methods are the str. format() method and the % operator.

What is the F-string concatenation in Python? ›

Concatenating Strings in Python Using f-Strings

Python f-strings are prefixed by the letter f and allow you to place variables to interpolate into square brackets. The variables are evaluated at run-time, and their string representation is placed into the string. print(f'Welcome to {website}!' )

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.

Should you use F-strings? ›

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).

What are the advantages of F-strings in Python? ›

Python f-strings provide a quick way to interpolate and format strings. They're readable, concise, and less prone to error than traditional string interpolation and formatting tools, such as the .format() method and the modulo operator ( % ). An f-string is also a bit faster than those tools!

How do you make an F-string have no new line in Python? ›

Using Backslashes

The backslashes tell Python to ignore the newline characters in the code and join the f-strings into one single line. Using backslashes, you can create multiline strings with f-strings without having to use triple quotes or escape characters. This can make your code more compact and efficient.

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 append to the F-string 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.

How do you format dates in Python F-string? ›

Formatting Dates With F-Strings

F-strings can also be used to format dates and times, using the built-in datetime module. To format a date or time using F-strings, simply include the object inside the curly braces, followed by a colon and the desired format specifier.

How does f-string work in Python? ›

In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.

What version of Python has F-string formatting? ›

F-string is a way to format strings in Python. It was introduced in Python 3.6 and aims to make it easier for users to add variables, comma separators, do padding with zeros and date format. F-string was introduced in Python 3.6 and provides a better way to format strings.

How do you escape a single quote in Python F-string? ›

Python f-string Escaping Characters

For this purpose, we make use of escape characters in f-string. To escape a curly bracket, we double the character. While a single quote is escaped using a backslash.

How are F-strings implemented in Python? ›

In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values. Some examples are: >>> import datetime >>> name = 'Fred' >>> age = 50 >>> anniversary = datetime.

What does .2f do in Python? ›

So %. 2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter.

How do you use quotes in F-string in Python? ›

We can use any quotation marks {single or double or triple} in the f-string. We have to use the escape character to print quotation marks. The f-string expression doesn't allow us to use the backslash. We have to place it outside the { }.

Top Articles
Latest Posts
Article information

Author: Carlyn Walter

Last Updated:

Views: 5944

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Carlyn Walter

Birthday: 1996-01-03

Address: Suite 452 40815 Denyse Extensions, Sengermouth, OR 42374

Phone: +8501809515404

Job: Manufacturing Technician

Hobby: Table tennis, Archery, Vacation, Metal detecting, Yo-yoing, Crocheting, Creative writing

Introduction: My name is Carlyn Walter, I am a lively, glamorous, healthy, clean, powerful, calm, combative person who loves writing and wants to share my knowledge and understanding with you.