write() 与 writelines() 和连接字符串 [英] write() versus writelines() and concatenated strings
问题描述
所以我正在学习 Python.我正在学习课程并遇到一个问题,我不得不将大量 target.write()
压缩成一个 write()
,同时有一个 "
"
在每个用户输入变量之间(write()
的对象).
So I'm learning Python. I am going through the lessons and ran into a problem where I had to condense a great many target.write()
into a single write()
, while having a "
"
between each user input variable(the object of write()
).
我想出了:
nl = "
"
lines = line1, nl, line2, nl, line3, nl
textdoc.writelines(lines)
如果我尝试这样做:
textdoc.write(lines)
我收到一个错误.但是如果我输入:
I get an error. But if I type:
textdoc.write(line1 + "
" + line2 + ....)
然后它工作正常.为什么我不能在 write()
中使用字符串作为换行符,但我可以在 writelines()
中使用它?
Then it works fine. Why am I unable to use a string for a newline in write()
but I can use it in writelines()
?
Python 2.7
推荐答案
writelines
需要一个可迭代的字符串write
需要一个字符串.writelines
expects an iterable of stringswrite
expects a single string.
line1 + "
" + line2
将这些字符串合并为一个字符串,然后将其传递给 write
.
line1 + "
" + line2
merges those strings together into a single string before passing it to write
.
请注意,如果您有很多行,您可能需要使用 "
".join(list_of_lines)
.
Note that if you have many lines, you may want to use "
".join(list_of_lines)
.
这篇关于write() 与 writelines() 和连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!