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

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

There is no difference at all. See the definition of Formatted string literals in the Python documentation. A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F'.

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 you quote an 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 { }.

How to use F-string in JSON Python? ›

You should use {{ to denote a literal { in f-strings, but @BrownieInMotion is right; you should use the data structure directly: data = [{"date": tomorrow, "price": {"amount": 15100}}] . requests. put will automatically use that, but if you must convert it to json use json. dumps(data) .

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}!' )

Should you always use F-strings in Python? ›

If you've been practicing Python for a while, you likely use " " to create strings in Python. There's nothing wrong with that. After all, our first line of Python code was a simple print(“Hello World”) . That said, if you want to take your Python strings to the next level, you should use f-strings.

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.

When was the f-string introduced in 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.

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.

What does .2f mean 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.

What is an example of an F-string 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.

How to escape in f-strings in Python? ›

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.

What is the F-string prefix in Python? ›

To use the f-strings in Python, you prefix the string with 'f' or 'F' and place any variables or expressions inside curly braces {}. Here is a basic example: name = "Alice" age = 30 print(f"My name is {name} and I am {age} years old.")

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 format F-string as a percentage in Python? ›

F-strings can also be used to format percentages, using the % format specifier. print(f"{x:. 2%} of the time, it works every time.")

References

Top Articles
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 6320

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.