Formatting Strings with f-strings in Python

Python Tips and Tricks
Published on: Apr 21, 2024
Last Updated: Jun 04, 2024

Introduction to f-strings

In Python 3.6, a new way of formatting strings was introduced called f-strings. Formatting strings in Python has always been a bit of a hassle, using the `.format()` method or the `%` operator. F-strings make it easier, more readable and faster to format strings in your code.

Basic usage of f-strings

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

This will print `Hello, John Doe!`. The value of the `name` variable is embedded in the string using the curly braces.

You can also perform operations inside the curly braces. For example, to create a string that contains the square of a number, you can use an f-string like this:

number = 5 print(f'The square of {number} is {number ** 2}.')

Formatting numbers and variables

You can format numbers inside f-strings using the standard formatting options for numbers. For example, to format a number with two decimal places, you can use the `:.2f` format specifier. Here's an example:

number = 3.14159 print(f'The number is {number:.2f}.')

You can also format variables inside f-strings. For example, to capitalize the first letter of a string, you can use the `.capitalize()` method. Here's an example:

name = 'john doe' print(f'The name is {name.capitalize()}')

This will print `The name is John doe.`.

Formatting with converters

You can use converters to format numbers and variables in specific ways. For example, you can use the `!s` converter to convert a number to a string, or the `!r` converter to convert an object to a string using its `repr()` method.

Here's an example:

number = 3 print(f'The number is {number!s}.')

This will print `The number is 3`.

You can also use converters with variables. Here's an example:

number = 3 print(f'The number is {number!r}.')

This will print `The number is 3`. The `!r` converter converts the number to a string using its `repr()` method.

Conclusion

F-strings are a great addition to the Python language. They make it easier, more readable and faster to format strings in your code. With f-strings, you can embed expressions inside curly braces and perform operations inside the curly braces. You can also format numbers and variables in specific ways using the standard formatting options for numbers, and converters.

F-strings are a powerful tool that can improve the readability and performance of your code. If you're writing Python 3.6 or newer, you should consider using f-strings in your code.