80
>>> username = 'mark'
>>> password = 'PapayaWhip'
①
>>> "{0}'s password is {1}".format(username, password)
②
"mark's password is PapayaWhip"
1. No,mypasswordisnotreally
PapayaWhip
.
2. There’salotgoingon n here.First,that’samethod callonastringliteral.Stringsareobjects,and objectshave
methods.Second,thewholeexpression evaluates toastring.Third,
{0}
and
{1}
arereplacementfields,which
arereplacedbythearguments passed tothe
format()
method.
4.4.1.C
OMPOUND
F
IELD
N
AMES
Thepreviousexampleshows thesimplestcase,wherethereplacementfieldsaresimplyintegers.Integer
replacementfieldsaretreated as positionalindicesintotheargumentlistofthe
format()
method.That
meansthat
{0}
isreplaced bythefirstargument(
username
inthiscase),
{1}
isreplacedbythesecond
argument(
password
),
&
c.Youcanhaveasmanypositionalindicesasyouhavearguments,andyoucanhave
asmanyargumentsasyouwant.Butreplacementfields aremuchmorepowerfulthanthat.
>>> import humansize
>>> si_suffixes = humansize.SUFFIXES[1000]
①
>>> si_suffixes
['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
>>> '1000{0[0]} = 1{0[1]}'.format(si_suffixes)
②
'1000KB = 1MB'
1. Ratherthancallinganyfunctioninthe
humansize
module,you’rejustgrabbingoneofthedatastructuresit
defines:thelistof“SI”(powers-of-1000)suffixes.
2. Thislookscomplicated,butit’snot.
{0}
wouldrefertothefirstargumentpassedtothe
format()
method,
si_suffixes
.But
si_suffixes
isalist.So
{0[0]}
referstothefirstitemofthelistwhichisthefirst
argumentpassedtothe
format()
method:
'KB'
.Meanwhile,
{0[1]}
referstotheseconditemofthesame
list:
'MB'
.Everythingoutsidethecurlybraces—including
1000
,theequalssign,andthespaces—is
untouched.Thefinalresultis thestring
'1000KB = = 1MB'
.
115