To add special formatting tags, just put a : inside the curly braces {} after your expression.
Sometimes you will have some long variables and short variables that will be displayed next to each other and you'll want them to line up properly. (This is especially important if you want to print something like a table.) You can do this by setting a minimum amount of space for your string to occupy.
Note: If your text is longer than the minimum space, it will continue beyond that space.
Look at the following:
f"My name is {name} and I am {age} years old."
Compared to:
f"My name is {name : 12} and I am {age : 4} years old."
Compare the output for those two strings with different sizes numbers and words.
Sometimes you will have limited space and will need to shorten overly long strings. You do this with a number after a decimal in your tags to indicate the maximum number of spaces your text can take up.
You can also combine minimum and maximum space by using numbers before and after a decimal point.
Compare the following:
f"My name is {name} and I am {age} years old."
f"My name is {name : .4} and I am {age} years old." (Maximum space)
f"My name is {name : 4} and I am {age} years old." (Minimum space.)
f"My name is {name : 4.4} and I am {age} years old." (Minimum and maximum space.)
If you have extra space because your string is not as long as the minimum space, you may want to choose how to justify your text.
These tags can change how your text is justified.
< left justify (this is done automatically with strings)
> right justify (this is done automatically with numbers)
^ center align
Observe the difference in these 4 strings:
f"My name is {name : 12} and I am {age : 4} years old."
f"My name is {name : <12} and I am {age : <4} years old."
f"My name is {name : >12} and I am {age : >4} years old."
f"My name is {name : ^12} and I am {age : ^4} years old."
Formatting floats works a little differently than formatting Strings. In the tags, the number after the decimal is your desired precision (bascially, your significant digits.)
Note: If displaying a float with a given precision would display it like an integer, Python will add a .0 to the end to make sure you know it's a float.
You can also use the e tag to make the float display in scientific notation.
Compare the following:
f"The square root of {number:8} is {math.sqrt(number)}." No formatting on the float.
f"The square root of {number:8} is {math.sqrt(number):.2}." 2 points of precision
f"The square root of {number:8} is {math.sqrt(number):.7}." 7 points of precision
f"The square root of {number:8} is {math.sqrt(number):10.4}." Minimum of 10 spaces, 4 points of precision.
f"The square root of {number:8} is {math.sqrt(number):10.4e}." Minimum of 10 spaces, 4 points of precision, scientific notation