Python f-Strings Tutorial – Better String Formatting

The f-strings are a new way to format strings in Python, introduced in version 3.6. They provide a more concise and readable way to embed expressions inside string literals, compared to the older methods of string formatting in Python. In this article, we will cover f-strings in detail and see how they differ from the older ways of formatting strings in Python.

The Old Ways of Formatting Strings in Python

Before the introduction of f-strings, there were two main ways to format strings in Python:

  1. String Concatenation
  2. % operator
  3. str.format() method

String Concatenation is the simplest way to format strings in Python. It involves joining strings using the ‘+’ operator. However, this method can become unreadable when dealing with large strings, especially when adding variables inside the string.

The % operator provides a more concise way to format strings. However, it has limited capabilities and is considered outdated. It is recommended to use the str.format() method instead.

The str.format() method provides a more powerful way to format strings, but it can become complex and difficult to read when dealing with complex expressions inside the string.

f-strings in Python

F-strings provide a way to embed expressions inside string literals in a more readable way. An f-string is a string literal that is prefixed with the letter ‘f’. The expressions inside an f-string are evaluated at runtime and their values are embedded inside the string.

Here’s the basic syntax of an f-string:

f'{expression}'

Where the expression can be any valid Python expression. The expression is evaluated and its value is added inside the string. For example:

name = 'John'
print(f'Hello, {name}!')

# Output: Hello, John!

In this example, the expression ‘name’ is evaluated and its value ‘John’ is embedded inside the string. The result is a string ‘Hello, John!’ that is printed to the console.

F-strings can also contain complex expressions, such as arithmetic operations, function calls, and more. For example:

a = 10
b = 20
print(f'The sum of {a} and {b} is {a + b}.')

# Output: The sum of 10 and 20 is 30.

In this example, the expression ‘a + b’ is evaluated and its value ’30’ is embedded inside the string. The result is a string ‘The sum of 10 and 20 is 30.’ that is printed to the console.

f-strings and Quotations

F-strings can contain both single and double quotes. If the f-string itself is enclosed in single quotes, expressions inside the f-string can be enclosed in double quotes, and vice versa. For example:

name = "John"
print(f"Hello, {name}!")
print(f'Hello, {name}!')
# Output:
# Hello, John!
# Hello, John!

In this example, both single and double quotes are used in the f-strings, and the expressions inside the f-strings are also enclosed in single and double quotes. The expressions are evaluated correctly and the output is as expected.

However, if an f-string itself contains both single and double quotes, it must be escaped with a backslash () to avoid a syntax error. For example:

name = "John"
print(f'Hello, "John" said: "My name is {name}".')
# Output:
# Hello, "John" said: "My name is John".

In this example, the f-string contains both single and double quotes, so they are escaped with a backslash to avoid a syntax error. The expression inside the f-string is evaluated correctly and the output is as expected.

Braces

Braces (i.e. curly brackets) are used to embed expressions inside f-strings. The expressions inside the braces are evaluated at runtime and their values are embedded inside the string. In case the expression inside the braces raises an error, the error will be raised at runtime, when the f-string is executed.

If we want to include a literal brace character inside an f-string, we can escape it by doubling it (i.e. ‘{{‘ and ‘}}’). For example:

print(f'{{10}}')
# Output: {10}

In this example, the expression ‘{{10}}’ is a literal brace character and its value is ‘{10}’, which is printed to the console.

We can also include expressions inside the literal braces. For example:

a = 10
print(f'{{{a}}}')
# Output: {10}

In this example, the expression ‘{{a}}’ is evaluated and its value ‘{10}’ is embedded inside the string, which is printed to the console.

It is important to note that the expressions inside the braces are evaluated in the current scope, meaning that any variable or function defined in the current scope can be used inside the braces.

In conclusion, braces are a powerful feature of f-strings that allow us to embed expressions inside string literals in a concise and readable way. They are evaluated at runtime and their values are embedded inside the string, making it easy to insert dynamic values inside a string.

Why f-strings are better?

F-strings offer several benefits over the older methods of formatting strings in Python:

  • Readability: F-strings provide a more concise and readable way to embed expressions inside string literals. They allow for an easier understanding of the code and make it easier to debug and maintain.
  • Performance: F-strings are faster than the str.format() method, making them the preferred method of string formatting in Python 3.6 and later.
  • Flexibility: F-strings allow for any valid Python expression to be evaluated and embedded inside the string, making them more flexible than the older methods of string formatting.

Examples of f-strings in Python

Let’s look at some more examples of using f-strings in Python:

Example 1: Formatting Numbers

F-strings can be used to format numbers as well. For example, you can specify the number of decimal places to be displayed using the format specifier. The format specifier is placed inside the expression and starts with a colon (:).

x = 3.14159265
print(f'The value of x is {x:.2f}')

# Output: The value of x is 3.14

In this example, the format specifier ‘.2f’ specifies that only 2 decimal places should be displayed. The value of x is 3.14159265, but when it is formatted using the f-string, only the first 2 decimal places are displayed.

Example 2: Formatting Dates and Times

F-strings can also be used to format dates and times. You can use the strftime() method of the datetime object to specify the format of the date and time.

from datetime import datetime
now = datetime.now()
print(f'The current date and time is {now.strftime("%Y-%m-%d %H:%M:%S")}')

# Output: The current date and time is 2023-02-08 09:42:48

In this example, the strftime() method is used to specify the format of the date and time. The format string ‘%Y-%m-%d %H:%M:%S’ specifies that the date and time should be displayed in the format ‘YYYY-MM-DD HH:MM:SS’.

Example 3: Using Variables Inside an f-string

F-strings can also be used to embed the values of variables inside the string. For example:

name = 'Jane'
age = 30
print(f'{name} is {age} years old.')
# Output: Jane is 30 years old.

In this example, the values of the variables ‘name’ and ‘age’ are embedded inside the string using an f-string.

Example 4: Using Expressions Inside an f-string

F-strings can also be used to embed the result of expressions inside the string. For example:

a = 10
b = 20
print(f'{a} + {b} = {a + b}')
# Output: 10 + 20 = 30

In this example, the expression ‘a + b’ is evaluated and its result ’30’ is embedded inside the string using an f-string.

Conclusion

In this article, we have covered f-strings in detail and seen how they provide a more concise and readable way to format strings in Python. We have also seen different examples of using f-strings, from formatting numbers and dates to embedding variables and expressions inside the string. F-strings are a new and improved way to format strings in Python and should be the preferred method for formatting strings in most cases.

Leave a Reply

Your email address will not be published. Required fields are marked *