Python - String format flags

Introduction

The following table lists the conversion type codes in formatting expressions.

They appear after the % character in substitution targets.

Some of the format codes in the table provide alternative ways to format the same type.

For instance, %e, %f, and %g provide alternative ways to format floating-point numbers.

Code Meaning
s String (or any object's str(X) string)
r Same as s, but uses repr, not str
c Character (int or str)
d Decimal (base-10 integer)
i Integer
u Same as d (obsolete: no longer unsigned)
o Octal integer (base 8)
x Hex integer (base 16)
X Same as x, but with uppercase letters
e Floating point with exponent, lowercase
E Same as e, but uses uppercase letters
f Floating-point decimal
F Same as f, but uses uppercase letters
g Floating-point e or f
G Floating-point E or F
% Literal % (coded as %%)

The general structure of conversion targets looks like this:

%[(keyname)][flags ][width][.precision]type-code 

The type code characters from the above table show up at the end of this target string's format. 

Between the % and the type code character, you can do any of the following: 
ItemDescription
keyname Provide a key name for indexing the dictionary used on the right side of the expression
flags space flags that specify things like left justification (-), numeric sign (+), a blank before positive numbers and a - for negatives (a space), and zero fills (0)
width a total minimum field width for the substituted text
.precisionSet the number of digits (precision) to display after a decimal point for floating-point numbers

Both the width and precision parts can be coded as a * to specify that they should take their values from the next item in the input values.

%s in the format string will be replaced by the corresponding value's default print string, regardless of its type.

Related Topic