6

I am starting to learn Python with an online guide, and I just did an exercise that required me to write this script:

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."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

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

I got it to run fine, but then the guide said: "There's too much repetition in this file. Use strings, formats, and escapes to print out line1, line2, and line3 with just one target.write() command instead of 6."

I'm not sure how to do this. Can anyone help? Thanks!

Joe Kington
  • 275,208
  • 71
  • 604
  • 463
Juan Soto
  • 61
  • 1
  • 1
  • 2
  • Do not use a volatile service like Pastebin for referencing code from within SO! –  Jun 18 '11 at 06:00
  • One can use `with open(path,'flags') as f: ... ... ...` and not have to worry about calling `f.close()` – ninjagecko Jun 18 '11 at 09:20

10 Answers10

16

The guide is suggesting creating a single string and writing it out rather than callingwrite() six time which seems like good advice.

You've got three options.

You could concatentate the strings together like this:

line1 + "\n" + line2 + "\n" + line3 + "\n"

or like this:

"\n".join(line1,line2,line3) + "\n"

You could use old string formatting to do it:

"%s\n%s\n%s\n" % (line1,line2,line3)

Finally, you could use the newer string formatting used in Python 3 and also available from Python 2.6:

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

I'd recommend using the last method because it's the most powerful when you get the hang of it, which will give you:

target.write("{0}\n{1}\n{2}\n".format(line1,line2,line3))
David Webb
  • 190,537
  • 57
  • 313
  • 299
5

How about

target.write('%s \n %s \n %s' % (line1,line2,line3))
Adithya Surampudi
  • 4,354
  • 1
  • 17
  • 17
1

This does it in two lines. It puts the line you want to print in a variable so it's more readable

lb = "\n"
allOnOne= line1 + lb + line2 + lb+ line3 + lb 
target.write(allOnOne) 
user2415706
  • 932
  • 1
  • 7
  • 19
1

I am currently following the same course, and the solution I found was similar to the one ninjagecko used, except I only used the things you were taught up to this point in the course. Mine looks like this:

from sys import argv
script, filename = argv
print "We're going to erase %s." % 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."

lines = [raw_input("Lines %r :" % i) for i in range(1, 4)]

for line in lines:
    target.write(line + "\n")

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

It took me awhile moving the parenthesis around and figuring out where to place the formatter and loop, but once I found it, it made perfect sense to me. One key thing to note is that my first attempt:

for i in range(1, 4):
    lines = raw_input("Line %r :" % i)

Appears to work at first when you run the script, however when you review the target file it only writes the last line (line3) to the file. I'm still not entirely clear on why that is the case.

Tyler
  • 90
  • 1
  • 7
  • Lovely post. I'd like to mention that you could fix your error in the last line by adding `target.write(lines + "\n")` inside the for loop right after what you wrote. Cheers – Kevin Zakka Aug 27 '15 at 09:09
1

I am just taking this course my self too for the first time and was wondering the same thing and this is what I figured out and got it to work with no issues. I am still learning this so if this is bad form let me know. Here is what I got to work for me.,

target.write("%s \n%s \n%s" % (line1,line2,line3))
Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
guy
  • 11
  • 1
1

For the purposes of "that specific study drill" question/problem in that specific guide, i believe the author would like...

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

Although, Dave Webb certainly gets many many browny points for being thorough plus educational value too.

1

I think they want you to use string concatenation:

target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")

Much less readable, but you have only one target.write() command

Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
0

I think the intent was for the student to leverage what had been taught in previous lessons and arrive at the following as a solution:

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."

target.write(line1 + '\n' + line2 + '\n' + line3 + '\n')

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

How about this? I used a for loop.

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 want that, hit RETURN.")

input("?")

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

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

print("Now I am going to ask you for three lines.")

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

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

for a in (line1, line2, line3):
    target.write("\n")

target.close()
  • Welcome to StackOverflow! I think you're not actually printing out the line. So, `target.write("\n")` would probably be `target.write (a + "\n")` (although I would recommend a better name than 'a'. – Nander Speerstra Jan 28 '19 at 16:29
0

bad

Original code is repetitive, and copy-pasting code is dangerous ( Why is "copy and paste" of code dangerous? ):

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."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

good

Much shorter, can change it to 4+ lines just by changing one character:

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

lines = [raw_input("line {i}: ".format(i=i)) for i in range(1,4)]

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

for line in lines:
    target.write(line+'\n')
Community
  • 1
  • 1
ninjagecko
  • 88,546
  • 24
  • 137
  • 145