用困难的方式学习Python,ex60 额外学分3
练习:
这个文件里有太多重复的内容。请使用字符串、格式和转义字符,只用一个target.write()命令来打印出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()
我的解决方案不管用。我在谷歌上搜索,想看看能不能用找到的东西来解决这个练习,但我还是没能写出正确的代码。这个练习的解决方案是什么呢?
1 个回答
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()。