Python 将由“\r\n”分隔的字符串拆分为行列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3345030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:33:01  来源:igfitidea点击:

Splitting a string separated by "\r\n" into a list of lines?

pythonstring

提问by ahhtwer

I am reading in some data from the subprocess module's communicate method. It is coming in as a large string separated by "\r\n"s. I want to split this into a list of lines. How is this performed in python?

我正在从子进程模块的通信方法中读取一些数据。它以一个由“\r\n”分隔的大字符串形式出现。我想把它分成一个行列表。这是如何在python中执行的?

采纳答案by Dave Kirby

Use the splitlines method on the string.

对字符串使用 splitlines 方法。

From the docs:

从文档:

str.splitlines([keepends])Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

str.splitlines([keepends])返回字符串中的行列表,在行边界处断开。结果列表中不包含换行符,除非给出了 keepends 并且为 true。

This will do the right thing whether the line endings are "\r\n", "\r" or "\n" regardless of the OS.

无论行尾是“\r\n”、“\r”还是“\n”,无论操作系统如何,这都会做正确的事情。

NB a line ending of "\n\r" will also split, but you will get an empty string between each line since it will consider "\n" as a valid line ending and "\r" as the ending of the next line. e.g.

注意 "\n\r" 的行结尾也将拆分,但每行之间会得到一个空字符串,因为它会将 "\n" 视为有效的行结尾,将 "\r" 作为下一行的结尾. 例如

>>> "foo\n\rbar".splitlines()
['foo', '', 'bar']

回答by tkerwin

s = re.split(r"[~\r\n]+", string_to_split)

This will give you a list of strings in s.

这将为您提供 s 中的字符串列表。

回答by wshato

Check out the doc for string methods. In particular the split method.

查看字符串方法的文档。特别是split方法。

http://docs.python.org/library/stdtypes.html#string-methods

http://docs.python.org/library/stdtypes.html#string-methods