f-string is the latest Python syntax to perform string formatting - They are called f-strings because you need to prefix a string with the letter f in order to get an f-string.
“F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. 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.”Source
The letter f also indicates that these strings are used for formatting.
f-string has been available since Python 3.6.
It is more readable, concise, faster and error-free than traditional string formatting.
# Format pi by changing precision
frommathimportpiforiinrange(1,7):print(f'{pi:.{i}f}')
1
2
3
4
5
6
3.1
3.14
3.142
3.1416
3.14159
3.141593
Padding numbers with zeros
You can pad any number with zeros by using f-strings. A well-known example is to append leading zeros to ID numbers. The purpose here is to have the numbers with the same length by using leading zeros.
1
f'{variable:0{width}}'
width is used to specify the total number of digits of a number after leading zeros.
# Find the longest id and pad with 0 in front of the numbers
product_ids=[93,123456789,5332493,32641,15279535]longest_product_id=len(max(map(str,product_ids),key=len))forproduct_idinproduct_ids:print(f'{product_id:0{longest_product_id}}')
1
2
3
4
5
000000093
123456789
005332493
000032641
015279535
Date time formatting
f-strings also support the formatting of datetime.
Dates are formatted the same way as numbers, using format specifiers.