-
Notifications
You must be signed in to change notification settings - Fork 0
strFormatting
Prefer f-strings where possible. They are easy to read and often provide performance benefits.
At {}
the given variable will be inserted.
"Hello {}!, I haven't seen you for {} days.".format("Joe", 5)
You can provide the argument number (starting by 0
).
"Hello {1}!, I haven't seen you for {2} days.".format("unused string", "Joe", 5)
References by name are also possible
"Hello {name}!, I haven't seen you for {time} days.".format(name="Joe", time=5)
Referencing and formattin gis separated by a colon (:
): e.g. {name:d}
, {:d}
, {1:d}
, ...
Only the remaining space is considered for alignment.
Option | Description |
---|---|
< | left aligned |
^ | centered |
> | right aligned |
= | signed; left aligned |
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.
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 in2.34
-
{:<pad>.<decimal-places>f}
e.g."{:2.2f}".format(2.3456)
results in2.34
(note the padding with spaces) -
{:<pad>.<decimal-places>f}
e.g."{:02f}".format(2.3456)
results in02
(note the padding with zeros) -
{:+f}
e.g."{:+f}".format(2.3456)
->+2
(note the padding with zeros)-
+
shows+
and-
-
-
shows only-
-
+
) 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******
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License *.
Code (snippets) are licensed under a MIT License *.
* Unless stated otherwise