[Tutor] String formatting question with 's'.format()

Alan Gauld alan.gauld at btinternet.com
Thu Jun 9 00:21:06 CEST 2011


<eizetov at gmail.com> wrote

>>>> 'first={0}, last={1}, middle={2}'.format(*parts)
> "first=S, last=M, middle=['P', 'A']"
>
> why do we need the '*' at 'parts'. I know we need it, because 
> otherwise it
> gives an error:

The * tells Python to unpack parts and treat the contents
as individual values. format is looking for 3 values. Without
the * it sees one, a tuple and complains about insufficient
values. If it did try to do the format you would wind up with
something like:

"first=(S,M,['P', 'A']) last=None, middle=None"

Python can't tell automatiocally whether you want the tuple
treated as a single value and youu just forgot the other two
or if you want the tuple unpacked. The * says unpack this value.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list