我正在学习使用“艰难学习python”的python,而我在exercise 16:学习练习时遇到了麻烦。如何将以下六行代码转换为一行? :
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
我接着尝试了这个:
lines = line1,"\n",line2,"\n",line3,"\n"
target.write(lines)
但这似乎也没有用,终端说: 期望一个字符缓冲对象
在参考练习6后,我尝试了:
lines = "%s\n%s\n%s\n" % line1,line2,line3
target.write(lines)
然后它在终端中说“TypeError:格式字符串没有足够的参数”
也尝试过:
target.write("%s,\n,%s,\n,%s,\n" % line1,line2,line3)
并遇到同样的问题
答案 0 :(得分:2)
答案 1 :(得分:1)
target.write('\n'.join(lines)) #assuming all the line #s are put in a list called "lines"
答案 2 :(得分:0)
这对我使用python 2.7
Lines = "%s\n%s\n%s" % (Line1, Line2, Line3)
target.write(Lines)
或
target.write("%s\n%s\n%s" % (Line1, Line2, Line3))
答案 3 :(得分:0)
阅读关于练习6的答案(我会评论我的帖子,但我不能:o)我写了这段代码:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
newline = "\n"
print "Now I 'm going to write these to the file."
target.write(line1 + newline + line2 + newline + line3 + newline)
它就像一个魅力!