Python String Formatting options (Document version 1.0 22.Sep
2000 by R.Kirsch)
%[(name)][flag][width][.precision][code]
>>> "%d_%c_%s" % (12.4,'A','abc')
'12_A_abc'
width
(non decimal): minimal total field width
| flag |
description |
format |
data |
output |
| - |
left justify |
'%-4d' |
12 |
'12 ' |
| + |
numeric sign |
'%+4d' |
12 |
' +12' |
| 0 |
zero fill |
'%04d' |
12 |
'0012' |
| flag |
description |
format |
data |
output |
| code |
description |
format |
data |
output |
| %c |
character |
'%4c' |
'a' |
' a' |
| %s |
string (or any object) |
'%5.3s' |
'abcd' |
' abc' |
| %i |
decimal integer |
'%5d' |
1234 |
' 1234' |
| %d |
decimal integer |
'%5i' |
1234 |
' 1234' |
| %u |
unsigned integer |
'%u' |
4.5 |
'4' |
| %o |
octal integer |
'%o' |
9 |
'11' |
| %x |
hex integer (lowercase) |
'%x' |
0x12ab |
'12ab' |
| %X |
hex integer (uppercase) |
'%X' |
0x12ab |
'12AB' |
| %e |
floating point |
'%e' |
1234.34 |
'1.234340e+03' |
| %E |
floating point |
'%E' |
1234.34 |
'1.234340E+03' |
| %f |
floating point |
'%f' |
1234.34 |
'1234.340000' |
| %g |
floating point |
'%g' |
1234.34 |
'1234.34' |
| %G |
floating point |
'%G' |
1234.34 |
'1234.34' |
| code |
description |
format |
data |
output |
%c - character
>>> '%c' % 'a'
'a'
>>> '%c' % 'abc'
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: %c requires int or char
>>> '%c' % '\x40'
'@'
>>> '%4c' % 'a'
' a'
String escape codes
| character |
description |
| \ |
(ignored) continuation character |
| \\ |
backslash |
| \' |
single quote |
| \" |
double quote |
| \a |
bell |
| \b |
backspace |
| \e |
escape key |
| \0 |
null (does not end string) |
| \n |
linefeed |
| \v |
vertical tab |
| \t |
horizontal tab |
| \r |
carriage return |
| \f |
formfeed |
| \0nn |
octal value |
| \xnn |
hex value |
| \other |
any other character |
| character |
description |
%s - string (or other expressions auto-converted to string)
>>> '%s' % 'hello, world'
'hello, world'
>>> '%10s' % 'hello, world'
'hello, world'
>>> '%.10s' % 'hello, world'
'hello, wor'
>>> '%-10s' % 'hello, world'
'hello, world'
>>> '%.15s' % 'hello, world'
'hello, world'
>>> '%-15s' % 'hello, world'
'hello, world '
>>> '%-15.10s' % 'hello, world'
'hello, wor '
>>> '%15.10s' % 'hello, world'
' hello, wor'
Usage of %% in formatting strings
represents a % character
>>> '%%%c' % 'A'
'%A'
Usage of (name):
>>> '%(n)d %(x)s' % {'n':4, 'x':'alfa'}
'4 alfa'