练习:
此文件中的重复次数过多。使用字符串,格式和转义只用一个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()
我的代码:
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()
我的解决方案不起作用。我和Google一起搜索,看看我是否可以用我在那里找到的东西来解决这个问题,但是我还没有找到正确的代码。 这个练习的解决方案是什么?
答案 0 :(得分:6)
您现在正在做的是将%格式化运算符应用于表达式
的结果target.write("%s\n,%s\n,%s\n")
您要做的是将%运算符应用于字符串
"%s\n%s\n%s\n" // Note that the code from the book doesn't print commas
然后将结果传递给target.write()。