尽情学习Python,ex60额外学分3

010*_*amt 0 python

行使:

这个文件中的重复次数太多了.使用字符串,格式和转义只用一个target.write()命令而不是6来打印line1,line2和line3.

书中的代码:

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()
Run Code Online (Sandbox Code Playgroud)

我的代码:

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("%s\n%s\n%s\n") %(line1,line2,line3)


print "And finally, we close it."
target.close()
Run Code Online (Sandbox Code Playgroud)

我的解决方案不起作用.我和Google一起搜索,看看我是否可以用我在那里找到的东西来解决这个问题,但是我还没有设法找到正确的代码.这个练习的解决方案是什么?

Pau*_*und 6

你现在正在做的是将%格式化运算符应用于表达式的结果

target.write("%s\n,%s\n,%s\n")
Run Code Online (Sandbox Code Playgroud)

您要做的是将%运算符应用于字符串

"%s\n%s\n%s\n"  // Note that the code from the book doesn't print commas
Run Code Online (Sandbox Code Playgroud)

然后将结果传递给target.write().