Total Python Noob:为什么这不起作用?

时间:2011-08-29 17:01:06

标签: python string line new-operator

我正在努力学习Python的艰难之路,并试图理解它,而不仅仅是锤击。我在练习16上遇到了困难,正如在SO上所讨论的那样:

Very basic Python question (strings, formats and escapes)

但我仍在试图弄清楚为什么这种方法不起作用:

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()

我为linebreak建立了一个值,并在target.write命令中使用%s调用line1,line2和linebreak值。当它被读取时,它不应该解析为“line1 \ n line2 \ n line3 \ n”吗?

这可能相当于一个孩子被问到什么能保持天空的东西,而且我为那种厚实而道歉。谢谢!

4 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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,其类型为NoneType,则错误消息可能对您更有意义。

答案 2 :(得分:0)

我几天前做过这个,在练习22中,他会要求你写下你到目前为止学到的所有内容并记住它。

早些时候他要求你评论每一行来解释它的作用。这可能是一个非常好的习惯,直到你知道线条做什么而不必考虑它们。

还要注意你如何陈述事情。

如果你想成为一名程序员,你需要开始像一个人一样说话并使用词汇。

line1,line2,line3,linebreak被称为变量。您暂时使用=(赋值运算符)给它们/赋值。

写是一个功能。 python中的函数在between()之间接受参数。 所有参数必须符合()。如果你像这样写它,我确定 不会绊倒你的。

stuffIWantToPrint = line1 + lb + line2 + lb+ line3 + lb #all strings together 
target.write(stuffIWantToPrint) #pass the big string to write

答案 3 :(得分:0)

我很晚但是你也这样做了: target.write("{line1}\n{line2}\n{line3}\n").format(line1=line1,line2=line2,line3=line3)