write() 与 writelines() 和连接字符串 [英] write() versus writelines() and concatenated strings

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

问题描述

所以我正在学习 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 strings
    • write 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆