wiki:python/Types/str/format

format, join, split, zfill


Python Doc > str.format()
Python Doc > Format String Syntax
Python Doc > Format Specification Mini-Language
Python PEP 3101


Suche formatstring für datetime-object
Re: zahlen in reihe und glied
Dive into Python 3: Formatting strings
Re: Formatierte Ausgabe vieler Variablen
verständnisfrage zu format()


Examples

Alignment & Filling

>>> '{0:<30}'.format('Hello!')
'Hello!                        '
>>> format('Hello!', '<30')
'Hello!                        '
>>> '{0:<10.8}'.format('Hello again!')
'Hello ag  '
>>> '{0:>10.8}'.format('Hello again!')
'  Hello ag'
>>> '{0:.8}'.format('Hello again!')
'Hello ag'
>>> '{0:>8}'.format('Hello again!')
'Hello again!'
>>> '{0:>30}'.format('Hello!')
'                        Hello!'
>>> '{0:^30}'.format('Hello!')
'            Hello!            '
>>> '{0:*^30}'.format('Hello!')
'************Hello!************'

Numbers

>>> '{:,}'.format(1234567890)
'1,234,567,890'
>>> '{:03d}'.format(3)
'003'
>>> '{:8d}'.format(8)
'       8'
# Note that `10` defines the length of the entire output
>>> '{:10.3f}'.format(2)
'     2.000'
>>> '{:010.3f}'.format(23.01)
'000023.010'
>>> '{0:.2%} of {1} are {2}'.format(points/total, total, points)
'88.64% of 22 are 19.5'

Datetime

>>> d = datetime.datetime.now()
>>> '{0:%Y.%m.%d %H:%M}'.format(d)
'2012.12.01 18:50'
>>> '{0:>30}'.format(d.strftime('%Y.%m.%d'))
'                    2012.12.01'

Helpfully ;-)

!r calls objects __repr__ method

>>> '{}'.format('any string')
'any string'
>>> '{!r}'.format('any string')
"'any string'"
Last modified 5 years ago Last modified on Apr 11, 2014, 9:53:01 AM