Python’s F-String Magic: Unleashing Hidden Tricks

Sachinjose
3 min readJun 25, 2024

--

Image by DALLE

In this blog, we’ll delve into the delightful world of f-strings, which was added in Python 3.6. If you’re still concatenating strings and variables using the plus sign or the `format()` method, prepare to be amazed by the simplicity and efficiency of f-strings!

What is f-strings?

F-strings offer a new way to format strings in Python. They are string literals that have an `f` at the beginning and curly braces containing expressions that will be replaced with their values. The result is a string where the expressions are evaluated at runtime and formatted using Python’s `str.format()` syntax.

How to use f-strings?

Using f-strings is as simple as prefixing your string with an `f` and writing your expressions inside ` {}`. Here are some examples:

name = “John Doe”
age = 28
print(f”Hi, {name}. You are {age} years old.”)

Output: `Hello, John. You are 28 years old. `

def calculate_sum(a, b):
return a + b

print(f"Sum of the number is {calculate_sum(2, 3)}")

Output: Sum of the number is 5

Advanced Formatting with f-strings

  1. Formatting of date time inside f-string

In Python, f-strings are a great way to format dates and times. You can embed expressions inside string literals, using `{}` brackets, to format dates and times directly

from datetime import datetime

now = datetime.now()
print(f"{now:%d-%m-%y}")
print(f"{now:%H-%M-%S}")
print(f"{now:%I}") # Hour
print(f"{now:%I%p}") # Hour with AM / PM

"""
Output:
22-06-24
19-51-30
07
07PM
"""

2. Floating point operations in f-string.

Formatting a floating-point decimal inside an f-string is quite straightforward. You can specify the precision of the decimal by including a colon and a dot followed by the number of decimal places you want. It’s a neat and efficient way to control the output of your strings, making sure they look just the way you need them to.

float_number = 1234.90123
print(f"{float_number:.3f}")
print(f"{float_number:.0f}")
"""
Output:
1234.901
1235
"""
float_number = 1234.90123
print(f"{float_number:_.3f}")
print(f"{float_number:,.3f}")

"""
output:
1_234.901
1,234.901
"""

3. Formatting of strings using f-strings

You can format numbers, adjust alignment, add padding, and much more. This will be helpful when we want to have the printed output in same length. For example:

variable = 'fstring'

# Right align
print(f"{variable:>20}:")
# fstring:

# Left align
print(f"{variable:<20}:")
# fstring :

# Center align
print(f"{variable:^20}:")
# fstring :
# Padding of outputs
print(f"{variable:#<20}")
# fstring#############

print(f"{variable:|>20}")
# |||||||||||||fstring

print(f"{variable:|^20}")
# ||||||fstring|||||||

print(f"{variable:&^20}")
# &&&&&&fstring&&&&&&&

print(f"{variable:*^20}")
# ******fstring*******

4. Handling of file paths

In Python, raw f-strings can be very useful for formatting file paths. By combining an ‘r’ to indicate a raw string with an ‘f’ for an f-string, you can include backslashes in your file paths without needing to escape them. This makes the code more readable and less prone to errors, especially when dealing with Windows file paths that often contain many backslashes.

path = rf"\home\users\workspace\sample"

5. Adding splitters between numbers.

f-strings are a great way to format strings efficiently and cleanly. By using a “splitter” inside an f-string, you can format numbers more readably, especially when dealing with large numbers.

number = 1000000000

print(f"{number:,}")
# Output: 1,000,000,000

print(f"{number:_}")
# Output: 1_000_000_000

Debugging with f-strings

One of the lesser-known but incredibly useful features introduced in Python 3.8 is the ability to use the `=` sign within an f-string to print both the expression and its value, which is a boon for debugging:


x = 3
print(f”{x=}”)

a = 6
b = 4
print(f"a + b = {a+b}")
print(f"{a + b = }")

"""
a + b = 10
a + b = 10
"""

This will output: `x=3`, showing both the variable name and its value.

a = 6.5
b = 4.2
print(f"{a + b =:.2f}")

This will output: a + b =10.70`.

Conclusion

F-strings are a powerful tool in Python’s arsenal, making string formatting more intuitive and efficient. They allow you to write cleaner code, which is easier to read and maintain.

Happy coding!

--

--