Vincent Touache - Character TD
/tutos/24_python_fstring_cheatsheet/content.php
data=================:ArrayPython's f-string cheatsheet

Table of Contents

  1. Basics
  2. Data types
  3. Combinations
  4. Create tables
  5. Debugging
  6. Conclusion



Basics

Let's define some dummy variables:

pi = 3.141592653589
answer = 42
heads_or_tails = .5
The 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|

Data types

You can format your variable based on their type and how you want to represent them

letterdata typeexampleresult
sstring
ffloating point number (default: 6 digits)print(f'pi is: {pi:.2f}')pi is: 3.14
bbinaryprint(f'answer is: {answer:b}')answer is: 101010
ooctalprint(f'answer is: {answer:o}')answer is: 52
xhexadecimalprint(f'answer is: {answer:x}')answer is: 2a
XHEXADECIMALprint(f'answer is: {answer:X}')answer is: 2A
ddecimalprint(f'answer is: {answer:d}')answer is: 42
nnumberprint(f'pi is: {pi:n}')pi is: 3.14159
eexponentprint(f'pi is: {pi:e}')pi is: 3.141593e+00
%percentage. Multiply by 100 and adds a % signprint(f'chances are: {heads_or_tails:.2%}')chances are: 50.00%

Combinations

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|

Create tables

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 

Debugging

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 

Conclusion

f-string is a powerful and ofter underestimated tool. You can take a look at this page for even more tips