Python - write()与writelines()和连接的字符串 [英] Python - write() versus writelines() and concatenated strings
问题描述
target.write()
压缩成一个 write()
,而在每个用户输入变量( write()$ c的对象)之间有一个\\\
我想出了:
nl =\\\
lines = line1,nl,line2,nl,line3,nl
textdoc.writelines(lines)
如果我尝试这样做:
$ p $ textdoc.write(lines)
我得到一个错误。但是,如果我输入:
textdoc.write(line1 +\ n+ line2 + ....)
然后工作正常。为什么我无法在 write()
中为换行使用字符串,但是我可以在 writelines()
?
Python 2.7
当我搜索到Google搜索到的大部分资源时,我发现它们是我的头,我仍然是一个非专业人士。
b $ b 解决方案 writelines 需要一个字符串列表,而 write
code>需要一个字符串。
$ b line1 +\ n+ line2
在将字符串传递给 write
。
请注意,如果您有很多行,可能需要使用 \\ n.join(list_of_lines)
。
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 "\n"
between each user input variable(the object of write()
).
I came up with:
nl = "\n"
lines = line1, nl, line2, nl, line3, nl
textdoc.writelines(lines)
If I try to do:
textdoc.write(lines)
I get an error. But if I type:
textdoc.write(line1 + "\n" + line2 + ....)
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
When I searched google most resources I found were way over my head, I'm still a lay-people.
解决方案 writelines
expects a list of strings, while write
expects a single string.
line1 + "\n" + line2
merges those strings together into a single string before passing it to write
.
Note that if you have many lines, you may want to use "\n".join(list_of_lines)
.
这篇关于Python - write()与writelines()和连接的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文