[Tutor] Are there other ways of solving this exercise?

Walter Prins wprins at gmail.com
Thu Jan 12 16:26:03 CET 2012


Hi amt,

On 12 January 2012 15:11, amt <0101amt at gmail.com> wrote:
> After reading from http://docs.python.org/library/stdtypes.html I came
> up with this:
>
> bag = "%s\n%s\n%s\n".format(line1,line2,line3)
> target.write(bag)
>
> Is this how it is supposed to look like using str.format?

Not quite.  The documentation states:

"str.format(*args, **kwargs): Perform a string formatting operation.
The string on which this method is called can contain literal text or
replacement fields delimited by braces {}. Each replacement field
contains either the numeric index of a positional argument, or the
name of a keyword argument. Returns a copy of the string where each
replacement field is replaced with the string value of the
corresponding argument."

So, this is different from the % operator, where format specifiers are
indicated with %.  Instead you need to use, as per the documentation,
curly braces e.g. {  and }.

You can easily test this in the Python interpreter e.g.:

>>> print "%s\n%s\n%s".format('aaa', 'bbb', 'ccc')
%s
%s
%s

(Hmm, does not work...)

>>> print '{0}\n{1}\n{2}'.format('aaa','bbb','ccc')
aaa
bbb
ccc

(Hmm, that does work!...)

Final comment, you can get rid of the variable "bag" by directly
printing the result of the call to format() like you did in your
previous solution.

Cheers,

Walter


More information about the Tutor mailing list