本文介绍了write()与writelines()和串联字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在学习Python.我正在上课,遇到了一个问题,我不得不将很多 target.write()压缩为一个 write(),而同时将>"\ n" 在每个用户输入变量( 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 "\n" between each user input variable(the object of write()).

我想到了:

nl = "\n"
lines = line1, nl, line2, nl, line3, nl
textdoc.writelines(lines)

如果我尝试这样做:

textdoc.write(lines)

我得到一个错误.但是如果我输入:

I get an error. But if I type:

textdoc.write(line1 + "\n" + 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

Python 2.7

推荐答案

  • writelines 需要一个可迭代的字符串
  • write 需要一个字符串.
    • writelines expects an iterable of strings
    • write expects a single string.
    • line1 +"\ n" + line2 将这些字符串合并为一个字符串,然后再传递给 write .

      line1 + "\n" + line2 merges those strings together into a single string before passing it to write.

      请注意,如果您有很多行,则可能要使用"\ n" .join(list_of_lines).

      Note that if you have many lines, you may want to use "\n".join(list_of_lines).

      这篇关于write()与writelines()和串联字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:37