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? ›

To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark in a print() statement. Inside this string, you can write a Python expression between { } 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.

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.

How do I use .2f in Python? ›

Explanation:
  1. format() method is called on the float value, specifying '{:.2f}' as the format specifier.
  2. {:.2f} format specifier indicates that the float should be formatted with two decimal places.
  3. The formatted value is stored in formatted_value.
  4. Finally, print() function is used to display the formatted value.

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

🔹 Quotation Marks in F-strings

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.

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!

What versions of Python support F-strings? ›

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.

Why put f before string Python? ›

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.

Are there F-strings in Python 2? ›

Because Python 2.7 will never support f-strings, there is nothing to be gained by being able to combine the 'f' prefix with 'u'.

What does 0.2 F do in Python? ›

%f is for floats. 02:01 In addition to the indicator, you can also put formatting information. The 0.2 here tells Python to put as many digits to the left of the decimal as you like, but only 2 significant digits to the right. 02:15 This formatting will work in more than just floats.

How to use an f string 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 3.2 F in Python? ›

It means print as a floating point at least 3 wide and a precision of 2. This is a format specifier of a floating point number with 2 decimals and at least one digit left of the decimal point. The number 12.34567 would be displayed as 12.35.

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

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 to use backslash in Python f-string? ›

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.

How do you write multiple lines of an F-string in Python? ›

To better understand the Python multiline string, below are the following approaches:
  1. Using Triple-Quotes.
  2. Using parentheses and single/double quotes.
  3. Using Backslash.
  4. Using Brackets.
  5. Using join()
  6. Using f-strings.
  7. Using string. format()
  8. Using %
Nov 29, 2023

What is the F-string in capital F? ›

An f-string is a string literal prefixed with the letter F, either in uppercase or lowercase. This kind of literal lets you interpolate variables and expressions, which Python evaluates to produce the final string. F-strings have gained a lot of popularity in the Python community since their introduction in Python 3.6.

How to use an f-string 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.

Why are F-strings faster? ›

Conciseness: F-strings provide a concise syntax for string formatting, reducing the amount of code required compared to other methods.

What is a string in Python? ›

In Python, a string is a sequence of characters. For example, "hello" is a string containing a sequence of characters 'h' , 'e' , 'l' , 'l' , and 'o' . We use single quotes or double quotes to represent a string in Python.

Top Articles
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 6352

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.