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

amt 0101amt at gmail.com
Thu Jan 12 16:11:23 CET 2012


On Thu, Jan 12, 2012 at 9:40 AM, Walter Prins <wprins at gmail.com> wrote:
> Hi,
>
> On 12 January 2012 14:24, amt <0101amt at gmail.com> wrote:
>>
>> target.write("%s\n%s\n%s\n" %(line1, line2, line3))
>>
>> This is the only method I was able to figure out of solving the exercise.
>>
>> Are there other ways of solving this exercise using strings, formats
>> and escapes like the author mentioned in the exercise question? If
>> yes, please write them.
>
>
> Firstly for those interested, I've tracked this down to "Learn Python
> The Hard Way, 2nd Edition".  (Amt, please include a reference if
> possible (especially when online) when you ask questions.)  The
> question is available here:
> http://learnpythonthehardway.org/book/ex16.html
>
> As for your question, I suppose using the string.format() method is
> another way that involves "strings, formats and escapes".  See here:
> http://docs.python.org/library/stdtypes.html  (and see the section on
> str.format therein. )
>
> Walter

Ok, I will keep that in mind.



After reading from http://docs.python.org/library/stdtypes.html I came
up with this:

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

bag = "%s\n%s\n%s\n".format(line1,line2,line3)
target.write(bag)

print "And finally, we close it."
target.close()


Is this how it is supposed to look like using str.format?




Thanks,amt.


More information about the Tutor mailing list