Show Menu
Cheatography

Python Format String Syntax Cheat Sheet (DRAFT) by

Python Format String Syntax

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Basic

{ [field­_name] [! conver­sion] [: format­_spec] }


-
field_name
: variable name
-
conversion
: pre-co­nvert the variable
-
format­_spec
: format the output

Conversion

s
Calls
str()
r
Calls
repr()
a
Calls
ascii()

Examples

'{:-<1­0}'.fo­rma­t('­abc')
'abc--­-----'
'{:,.2­f}'.fo­rma­t(1­234­5.6789)
'12,34­5.68'

Type

f / F
Floating point
d
Integer (decimal - default for int)
%
Percentage
b
Binary
o
Octal
x / X
Hex
e / E
Expone­ntial
g / G
General (default for float)
n
number (generic)
c
character (unicode)
 

Format Specif­ication

: [align­][s­ign­][w­idt­h][­opt­ion­s][.pr­eci­sio­n][­type]

Align

fill
Any character to fill any extra space (precedes the alignment character)
<
left-a­ligned (default for objects)
>
right-­aligned (default for numbers)
^
centered
=
fill space between sign and number

Sign

+
both positive and negative sign are shown
-
only negative sign is shown
" "
space for positive, "­-" for negative

Options

#
Alternate form (*before width)
,
Adds "­," as thousands separator
_
Adds "­_" as thousands separator