Skip to content

strFormatting

holzkohlengrill edited this page Dec 15, 2023 · 2 revisions

Python String formatting

F-strings

Prefer f-strings where possible. They are easy to read and often provide performance benefits.

.format()

Variable referencing

Implicit referencing

At {} the given variable will be inserted.

"Hello {}!, I haven't seen you for {} days.".format("Joe", 5)

Positional referencing

You can provide the argument number (starting by 0).

"Hello {1}!, I haven't seen you for {2} days.".format("unused string", "Joe", 5)

Keyword referencing

References by name are also possible

"Hello {name}!, I haven't seen you for {time} days.".format(name="Joe", time=5)

Formatting

Referencing and formattin gis separated by a colon (:): e.g. {name:d}, {:d}, {1:d}, ...

Alignment

Only the remaining space is considered for alignment.

Option Description
< left aligned
^ centered
> right aligned
= signed; left aligned

Numbers

General options
Option Description
d dec
c unicode char
b bin
o oct
x / X hex
e / E exp notation
f / F Float (default=6, F: inf -> INF; nan -> NAN)
g "general"; rounds to significant digits (default=6)
G Same as g; auto-switches to 'E' if useful
% percentage

All upper case options return the corresponding upper case output.

Padding/width (int & float); sign

If the number would not be displayable the relevant formatting options get ignored.

  • {:<pad>.<decimal-places>f} e.g. "{:2.2f}".format(2.3456) results in 2.34
  • {:<pad>.<decimal-places>f} e.g. "{:2.2f}".format(2.3456) results in 2.34 (note the padding with spaces)
  • {:<pad>.<decimal-places>f} e.g. "{:02f}".format(2.3456) results in 02 (note the padding with zeros)
  • {:+f} e.g. "{:+f}".format(2.3456) -> +2 (note the padding with zeros)
    • + shows + and -
    • - shows only -
    • (space) shows a padding space (in case of +) otherwise -

For strings <decimal-places> can be seen as truncating the string

Some more complex examples:

  • "{:^8.2f}".format(-34.6841)) results in -34.68
  • "{:*^-18.2f}".format(-34.6841) results in ******-34.68******
Clone this wiki locally