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

amt 0101amt at gmail.com
Thu Jan 12 17:57:21 CET 2012

I'll give it another try:

On Thu, Jan 12, 2012 at 10:26 AM, Walter Prins <wprins at gmail.com> wrote:
> 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!...)
So the code should look like this:

bag = "{0}\n{1}\n{2}".format(line1,line2,line3)

> 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

You mean print "{0}\n{1}\n{2}\n".format(line1,line2,line3)?

Ok, but if I drop the variable bag and print directly,how will I write
line1,line2,line3 in the .txt file since I have no parameter to give
to the write method.(target.write() ) ?

Walter, thanks a lot for taking your time to help me out.

Cheers, amt.

More information about the Tutor mailing list