完全的Python新手:为什么这不管用?
我正在学习《Learn Python the Hard Way》,想要真正理解它,而不是只是一味地敲代码。我在第16个练习上卡住了,之前在Stack Overflow上也讨论过这个问题:
但我还是在努力弄明白为什么这个方法不奏效:
from sys import argv
script, filename = argv
print "Attempting to open the file now."
print open(filename).read()
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-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."
linebreak = "\n"
target.write("%s %s %s %s %s %s") % (line1, linebreak, line2, linebreak, line3, linebreak)
target.write("the ending line")
print "And finally, we close it."
target.close()
我已经为换行符设置了一个值,并在target.write命令中用%s调用了line1、line2和linebreak的值。难道在读取时它不应该解析成“line1 \n line2 \n line3 \n”吗?
这可能就像小孩问你天空为什么会悬在那样,我为自己有点笨而感到抱歉。谢谢!
4 个回答
0
我几天前做了这个练习,在第22题里,他会让你把到目前为止学到的所有东西写下来并记住。
之前他还要求你给每一行代码加注释,解释它的作用。这其实是个很好的习惯,直到你能不假思索地知道每行代码在做什么。
另外,表达方式也要注意。
如果你想成为程序员,就需要开始用程序员的方式说话,使用相关的词汇。
line1、line2、line3和linebreak被称为变量。你可以用=(赋值符号)给它们暂时赋值。
Write是一个函数。在Python中,函数的参数放在()里面。所有的参数都必须放在()里。如果你这样写的话,我相信你不会搞错。
stuffIWantToPrint = line1 + lb + line2 + lb+ line3 + lb #all strings together
target.write(stuffIWantToPrint) #pass the big string to write
7
假设你得到了
TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
你需要的是
target.write("%s %s %s %s %s %s" % (line1, linebreak, line2, linebreak, line3, linebreak))
也就是说,你需要在字符串上使用 %
操作符,而不是在 target.write()
的结果上使用。错误信息可能会更容易理解,如果你知道 target.write()
返回的是 None
,而 None
的类型是 NoneType
。
9
target.write("%s %s %s %s %s %s") % (line1, linebreak, line2, linebreak, line3, linebreak)
应该是
target.write("%s %s %s %s %s %s" % (line1, linebreak, line2, linebreak, line3, linebreak))
但更好的写法是:
target.write(' '.join(line1, linebreak, line2, linebreak, line3, linebreak))