Chap_3 Cheat Sheet

A Programming › Python cheat sheet in English by Theo666

Affichage : print & f-string

2,229 views 792 downloads 25 Sep 2023 History

Function print()

value
One or more values to be printed. These can be of any data type, like str, list, etc
sep
Separator between each value. A space by default
end
String to be printed at the end of the output. '­\n' by default
file
Where the output will be printed. the console by default
print(­value, ..., sep, end, file, flush)
print(­'­Hello, world!­', file=f, end = "­") equal to f.writ­e('H­ello, world!­')

f-string (old version)

% under version 2.6
"%s ... text ... %d ...text... %.2f" % (var1, var2, var3)
the % symbol is used as a string formatting operator. The tuple at the end is applied. %s for string variable; %d for an integer; %.nf for float with n demical places
.format() version 2.7 - 3.5
"{} ... {.6e} ... {:.2f}­­".f­o­r­ma­­t(var1, var2, var3)
the {} symbol is used as a string formatting operator. format() at the end. {} for an integer, {.6e} for a number in scientific format with 6 demical places, etc

f-string version 3.5+

f"...te­xt...{­var­iab­le}...t­ex­t..."
f"{v­ari­abl­e:^­n}"
center within a field of width n
f"{v­ari­abl­e:s­ymb­ole­^n}­"
f"{v­ari­abl­e:<­n}"
leftalign within a field of width n
f"{v­ari­abl­e:>­n}"
rightalign within a field of width n
f"{v­ari­abl­e:n­}"
equal to f"{v­ari­abl­e:>­n}"
f"{v­ari­able:d}
integer = int()
{varia­ble­:.n­f}"
floati­ng-­number with n demical places
f"{v­ari­abl­e:e­}"
scientific format
f"{v­ari­abl­e:n­e}"
scientific format with n demical places
f"{v­ar:.{i­nt}­f}"
To combine multiple formats, the order is as follows : width, demical places, scientific format

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.