在Python中使用换行符分隔字符串


101

我需要定界包含新行的字符串。我将如何实现?请参考下面的代码。

输入:

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

所需的输出:

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

我尝试了以下方法:

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

1
输出是repr(data)什么?
Ashwini Chaudhary 2014年

Answers:


187

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']

6
其中一个方便的部分str.splitlines是,\n如果存在决赛,它将删除决赛。即,'foo\nbar\n'.split() == ['foo', 'bar', '']str.splitlines('foo\nbar\n') == ['foo', 'bar']
马修·莫森

10
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,默认情况下,按所有空白字符分割。如果实际的字符串还有其他空格字符,则可能要使用

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

或者按照评论中的@Ashwini Chaudhary的建议,可以使用

print(data.splitlines())

只是为了安全起见.splitlines,如果字符串中有空格等,该怎么办?
Ashwini Chaudhary 2014年

@AshwiniChaudhary是,这就是为什么我建议的原因split("\n")。是splitlines不是更好.split("\n")
thefourtheye 2014年

4
它也适用于\r\n其他类型的线边界。
Ashwini Chaudhary 2014年

如果您的字符串以结尾\nsplitlines()则将其忽略,而结果的末尾split("\n")将有一个空字符串""
Moberg

10

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

例:

>>> 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']

使用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']

然而:

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

您不必通过字符来拆分就好像很奇怪data.split('\n')吗?

7

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

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

4

干得好:

>>> 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 using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.