这是我的原始代码,可以在Python上正常运行:
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()
然后我试图清理重复:
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()
由于某些原因,新代码没有完全运行,它会到达第27行然后返回
TypeError:%支持的操作数类型:' NoneType'和' str'
有关如何纠正此问题的任何想法?
我对编码非常陌生,我正在学习使用Zed Shaw"艰难的学习代码"来学习编码,所以对此有任何帮助将非常感激
答案 0 :(得分:1)
看起来您的行target.write("%s \n%s \n%s \n") % (line1, line2, line3)
就是问题所在。
在进行变量替换之前,您已关闭write
函数调用。因此变量line1,line2和line3没有被插入%s' s。因此,您有一堆None
正在写入而导致错误。
将其更改为:
target.write("%s \n%s \n%s \n" % (line1, line2, line3))
答案 1 :(得分:0)
%
是一个字符串运算符;您正尝试将其与target.write()
的返回值一起使用。
target.write("%s \n%s \n%s \n" % (line1, line2, line3))
如果您刚刚开始,我建议您切换到Python 3.5和str.format
语法。这样,你就不会有过早关闭括号的问题:
target.write("{0} \n{1} \n{2} \n".format(line1, line2, line3))
3.6版本目前正在开发并开始进行beta测试,它将有一种更自然的语法来构建这种名为f strings的字符串:
target.write(f'{line1}\n{line2}\n{line3}\n')