Let's define some dummy variables:
pi = 3.141592653589 answer = 42 heads_or_tails = .5The most standard thing to do is adding spaces before or after:
print(f'pi is: {my_var}') print(f'pi is: |{my_var:->20}|')The syntax is as follow: variable : optional[separator] optional[align-operator] optional[number_of_characters]
Example:
print(f'answer is: |{answer:->20}|') >>> answer is: |------------------42|
You can format your variable based on their type and how you want to represent them
letter | data type | example | result |
---|---|---|---|
s | string | ||
f | floating point number (default: 6 digits) | print(f'pi is: {pi:.2f}') | pi is: 3.14 |
b | binary | print(f'answer is: {answer:b}') | answer is: 101010 |
o | octal | print(f'answer is: {answer:o}') | answer is: 52 |
x | hexadecimal | print(f'answer is: {answer:x}') | answer is: 2a |
X | HEXADECIMAL | print(f'answer is: {answer:X}') | answer is: 2A |
d | decimal | print(f'answer is: {answer:d}') | answer is: 42 |
n | number | print(f'pi is: {pi:n}') | pi is: 3.14159 |
e | exponent | print(f'pi is: {pi:e}') | pi is: 3.141593e+00 |
% | percentage. Multiply by 100 and adds a % sign | print(f'chances are: {heads_or_tails:.2%}') | chances are: 50.00% |
print(f'chances are: |{heads_or_tails:-^20%}|') >>> chances are: |-----50.000000%-----|
print(f'pi x 1000 is: |{pi*1e4:,.2f}|') >>> pi x 1000 is: |31,415.93|
print(f'pi x 1000 is: |{pi*1e4:+,.2f}|') >>> pi x 1000 is: |+31,415.93|
print(f'Number\t\tSquare\t\t\tCube') for x in range(1, 4): x = float(x) print(f'{x:5.2f}\t\t{x*x:^12.2f}\t{x*x*x:.2e}') >>> Number Square Cube 1.00 1.00 1.00e+00 2.00 4.00 8.00e+00 3.00 9.00 2.70e+01
This is available only on python 3.9+
random_operation = (42*3.1415)**0.5 print(f'{random_operation = }') >>> random_operation = 11.486644418628098 print(f'{random_operation = :.6e}') >>> random_operation = 1.148664e+01
f-string is a powerful and ofter underestimated tool. You can take a look at this page for even more tips