Fun with Fstrings
The most common use of fstrings is print(f'{var}')
In [1]:
author = 'Patrick'
year = 2024
print(f"Example 1: {author}") # string
print(f"Example 2: {year}") # number
print(f"Example 3: {2 + 2}") # expression
Example 1: Patrick Example 2: 2024 Example 3: 4
But there is much more that can be used, like if you want to output a float. by adding :.0f
after the variable name we can change how many digits get printed to the screen.
In [3]:
pi_val = 3.141592
print(f"Example 1: {pi_val:f}")
print(f"Example 2: {pi_val:.0f}")
print(f"Example 3: {pi_val:.1f}")
print(f"Example 4: {pi_val:.3e}")
Example 1: 3.141592 Example 2: 3 Example 3: 3.1 Example 4: 3.142e+00
We can use this same logic to make our percentages look nicer.
In [6]:
val = .5
print(f'Example 1: {val:%}')
print(f'Example 2: {val:.0%}')
print('\n')
val = .5678900
print(f'Example 1: {val:%}')
print(f'Example 2: {val:.0%}')
print(f'Example 2: {val:.3%}')
Example 1: 50.000000% Example 2: 50% Example 1: 56.789000% Example 2: 57% Example 2: 56.789%
One formatting that I enjoy is being able to add ,
to large numbers. This makes it easier to read and adds a level of professionalism.
In [12]:
int1 = 1000
int2 = 10000000
print(f'Example 1: {int1:,d}')
print(f'Example 1: {int2:,d}')
Example 1: 1,000 Example 1: 10,000,000
last two things are about padding. I have never used this, but I know it is a great trick to have in your pocket.
In [13]:
val = 1
print('Padding with white space')
print(f"1: {val:1d}")
print(f"2: {val:2d}")
print(f"3: {val:3d}")
print('\n')
print('Padding with zeros')
print(f"1: {val:01d}")
print(f"2: {val:02d}")
print(f"3: {val:03d}")
Padding with white space 1: 1 2: 1 3: 1 Padding with zeros 1: 1 2: 01 3: 001