使用 Python 的换行符分割字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22042948/
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-19 00:08:03  来源:igfitidea点击:

Split string using a newline delimiter with Python

pythonstringpython-2.7

提问by Hariharan

I need to delimit the string which has new line in it. How would I achieve it? Please refer below code.

我需要分隔包含新行的字符串。我将如何实现它?请参考以下代码。

Input:

输入:

data = """a,b,c
d,e,f
g,h,i
j,k,l"""

Output desired:

所需的输出:

['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

I have tried the below approaches:

我尝试了以下方法:

1. output = data.split('\n')
2. output = data.split('/n')
3. output = data.rstrip().split('\n')

采纳答案by wim

str.splitlinesmethod should give you exactly that.

str.splitlines方法应该给你。

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

回答by thefourtheye

data = """a,b,c
d,e,f
g,h,i
j,k,l"""

print(data.split())       # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

str.split, by default, splits by all the whitespace characters. If the actual string has any other whitespace characters, you might want to use

str.split,默认情况下,按所有空白字符拆分。如果实际字符串有任何其他空白字符,您可能需要使用

print(data.split("\n"))   # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

Or as @Ashwini Chaudhary suggested in the comments, you can use

或者正如@Ashwini Chaudhary 在评论中建议的那样,您可以使用

print(data.splitlines())

回答by Games Brainiac

Here you go:

干得好:

>>> data = """a,b,c
d,e,f
g,h,i
j,k,l"""
>>> data.split()  # split automatically splits through \n and space
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
>>> 

回答by pajton

There is a method specifically for this purpose:

有一种专门用于此目的的方法:

data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

回答by KiraLT

If you want to split only by newlines, its better to use splitlines():

如果您只想按换行符拆分,最好使用splitlines()

Example:

例子:

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

With split() it works also:

使用 split() 也可以:

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.split()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

However:

然而:

>>> data = """
... a, eqw, qwe
... v, ewr, err
... """
>>> data
'\na, eqw, qwe\nv, ewr, err\n'
>>> data.split()
['a,', 'eqw,', 'qwe', 'v,', 'ewr,', 'err']