o'reilly's learn python powerful object oriented programming mark lutz teaches different ways format strings.
this following code has me confused. interpreting 'ham' filling format place marker @ index zero, , yet still pops @ index 1 of outputted string. please me understand going on.
here code:
template = '{motto}, {0} , {food}' template.format('ham', motto='spam', food='eggs')
and here output:
'spam, ham , eggs'
i expected:
'ham, spam , eggs'
the thing have understand {0}
refers first (zeroeth) unnamed argument sent format()
. can see case removing unnamed references , trying use linear fill-in:
>>> "{motto}".format("boom") traceback (most recent call last): file "<stdin>", line 1, in <module> keyerror: 'motto'
you expect 'boom' fill in 'motto' if how works. but, instead, format()
looks parameter named 'motto'. key hint here keyerror
. similarly, if taking sequence of parameters passed format()
, wouldn't error, either:
>>> "{0} {1}".format('ham', motto='eggs') traceback (most recent call last): file "<stdin>", line 1, in <module> indexerror: tuple index out of range
here, format()
looking second unnamed argument in parameter list - doesn't exist gets 'tuple index out of range' error. difference between unnamed (which positionally sensitive) , named arguments passed in python.
see post understand difference between these types arguments, known 'args' , 'kwargs'.
Comments
Post a Comment