String interpolation is a way to embed variables into strings. It makes it easy to manipulate and enrich strings. Thus, the print statements are much more powerful with string interpolation.
Formatted string literals, also known as f-strings, are a highly practical method for string interpolation. They use curly braces as variable placeholders.
In this article, we will go over 4 tricks to use f-strings more efficiently. Let’s start with a simple example to demonstrate how f-strings work.
age = 24
print(f"John is {age} years old.")
John is 24 years old.
1. Format large numbers
When working with large numbers, it is better to use thousands separators for better readability. F-strings make it quite simple to place these separators appropriately.
Here is how it looks without the thousands separators:
number = 3454353453
print(f"The value of the company is {number}")
The value of the company is 3454353453
Let’s place the separators and see the difference.
print(f"The value of the company is {number:,d}")
The value of the company is 3,454,353,453
2. Format dates
There are various ways to represent dates in our scripts. It depends on the geographical location or just your preferences.
We can place dates in f-strings without formatting just like any other variable.
from datetime import datetime
today = datetime.today().date()
print(f"Today is {today}")
Today is 2021-06-23
The following might be a better representation in some cases.
print(f"Today is {today:%B %d, %Y}")
Today is June 23, 2021
If you live in a country where the month is written before the day, you can use the following formatting.
print(f"Today is {today:%m-%d-%Y}")
Today is 06-23-2021
3. Pad numbers
In some cases, numbers are written with leading zeros in order to have the same number of digits for all numbers. Typical use cases might be product numbers or id numbers.
We can place any number of leading zeros for a variable in f-strings.
a = 4
b = 123
print(f"Product numbers are n{a:03} n{b:03}")
Product numbers are
004
123
"b:03" indicates that there will be a total of 3 digits and leading spaces will be padded with zero. In case of a one-digit number, we have 2 leading zeros. If it was "b:04", the number would be written as 0004 and 0123.
4. Write expressions
The f-strings also allow for using expressions in variable placeholders. These expressions can involve function executions. It is a handy feature because we do not need to create variables for values that are used only once.
Let’s do an example that contains a date manipulation.
from datetime import datetime, timedelta
today = datetime.today().date()
print(f"The test was 3 days ago which is {today - timedelta(days=3)}")
The test was 3 days ago which is 2021-06-20
Another example can be finding the number of items in a list and using it as a variable.
mylist = [1, 2, 4, 6, 3]
print(f"The list contains {len(mylist)} items.")
The list contains 5 items.
Conclusion
Strings are an important part of our scripts. We also use them along with the print statement for debugging purposes. String interpolation helps us make the most out of the print statement. It allows for manipulating or customizing strings easily.
F-strings provide a clean syntax and easy-to-read code for string interpolation. The tricks we have covered in the article add more flexibility on the standard use of f-strings.
Thank you for reading. Please let me know if you have any feedback.