如何在python中将多行字符串拆分为多行?

时间:2017-09-15 07:38:31

标签: python

我有一个多行字符串:

inputString = "Line 1\nLine 2\nLine 3"

我想要一个数组,每个元素最多有两行,如下所示:

outputStringList = ["Line 1\nLine2", "Line3"]

我可以在python中将inputString转换为outputStringList。任何帮助将不胜感激。

7 个答案:

答案 0 :(得分:3)

您可以尝试找到2行(其中包含前瞻以避免捕获换行符)或仅查找一行(处理最后一行奇数行)。我扩展了你的例子,表明它适用于超过3行(有一点"作弊":最后添加一个换行符来处理所有情况:

import re

s = "Line 1\nLine 2\nLine 3\nline4\nline5"
result = re.findall(r'(.+?\n.+?(?=\n)|.+)', s+"\n")

print(result)

结果:

['Line 1\nLine 2', 'Line 3\nline4', 'line5']

"添加新行作弊"允许正确处理:

    s = "Line 1\nLine 2\nLine 3\nline4\nline5\nline6"

结果:

['Line 1\nLine 2', 'Line 3\nline4', 'line5\nline6']

答案 1 :(得分:2)

以下是使用grouper itertools recipe将任意数量的行组合在一起的替代方法。

注意:您可以手动实施此配方,也可以选择安装为您实现此配方的第三方库,即pip install more_itertools

<强>代码

from more_itertools import grouper


def group_lines(iterable, n=2):
    return ["\n".join((line for line in lines if line))
                    for lines in grouper(n, iterable.split("\n"), fillvalue="")]

<强>演示

s1 = "Line 1\nLine 2\nLine 3"
s2 = "Line 1\nLine 2\nLine 3\nLine4\nLine5"


group_lines(s1)
# ['Line 1\nLine 2', 'Line 3']

group_lines(s2)
# ['Line 1\nLine 2', 'Line 3\nLine4', 'Line5']

group_lines(s2, n=3)
# ['Line 1\nLine 2\nLine 3', 'Line4\nLine5']

<强>详情

group_lines()将字符串拆分为多行,然后通过ngrouper分组。

list(grouper(2, s1.split("\n"), fillvalue=""))
[('Line 1', 'Line 2'), ('Line 3', '')]

最后,对于每组行,只有非行为字符串与换行符重新连接。

有关grouper的详细信息,请参阅more_itertools docs

答案 2 :(得分:1)

我希望我的逻辑正确 - 如果你想要一个字符串列表,每个字符串都有最多一个换行符分隔符,那么以下代码片段将起作用:

# Newline-delimited string
a = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7"
# Resulting list
b = []

# First split the string into "1-line-long" pieces
a = a.split("\n")

for i in range(1, len(a), 2):

    # Then join the pieces by 2's and append to the resulting list
    b.append(a[i - 1] + "\n" + a[i]) 

    # Account for the possibility of an odd-sized list
    if i == len(a) - 2: 
        b.append(a[i + 1])

print(b)

>>> ['Line 1\nLine 2', 'Line 3\nLine 4', 'Line 5\nLine 6', 'Line 7']

虽然这个解决方案不是最快的也不是最好的,但它很容易理解,并且不涉及额外的库。

答案 3 :(得分:1)

我也希望从itertools文档发布石斑鱼食谱,但PyToolz' partition_all实际上更好一些。

from toolz import partition_all

s = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5"
result = ['\n'.join(tup) for tup in partition_all(2, s.splitlines())]
# ['Line 1\nLine 2', 'Line 3\nLine 4', 'Line 5']

为了完整起见,这是grouper解决方案:

from itertools import zip_longest

# Recipe from the itertools docs.
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

result = ['\n'.join((a, b)) if b else a for a, b in grouper(s, 2)]

答案 4 :(得分:-1)

使用str.splitlines()将完整输入拆分为行:

>>> inputString = "Line 1\nLine 2\nLine 3"
>>> outputStringList = inputString.splitlines()
>>> print(outputStringList)
['Line 1', 'Line 2', 'Line 3']

然后,加入第一行以获得所需的结果:

>>> result = ['\n'.join(outputStringList[:-1])] + outputStringList[-1:]
>>> print(result)
['Line 1\nLine 2', 'Line 3']

奖励:为任意数量的所需行编写一个相同的函数:

def split_to_max_lines(inputStr, n):
    lines = inputStr.splitlines()
    # This define which element  in the list become the 2nd in the
    # final result. For n = 2, index = -1, for n = 4, index = -3, etc.
    split_index = -(n - 1)
    result = ['\n'.join(lines[:split_index])]
    result += lines[split_index:]
    return result

print(split_to_max_lines("Line 1\nLine 2\nLine 3\nline 4\nLine 5\nLine 6", 2))
print(split_to_max_lines("Line 1\nLine 2\nLine 3\nline 4\nLine 5\nLine 6", 4))
print(split_to_max_lines("Line 1\nLine 2\nLine 3\nline 4\nLine 5\nLine 6", 5))

返回:

['Line 1\nLine 2\nLine 3\nline 4\nLine 5', 'Line 6']
['Line 1\nLine 2\nLine 3', 'line 4', 'Line 5', 'Line 6']
['Line 1\nLine 2', 'Line 3', 'line 4', 'Line 5', 'Line 6']

答案 5 :(得分:-1)

b = "a\nb\nc\nd".split("\n", 3)
c = ["\n".join(b[:-1]), b[-1]]
print c

给出

['a\nb\nc', 'd']

答案 6 :(得分:-2)

我不确定你的意思&#34;最多2行&#34;以及你希望如何实现这一目标。但是,拆分换行很简单。

'Line 1\nLine 2\nLine 3'.split('\n')

这将导致:

['line 1', 'line 2', 'line 3']

获得#34;某些&#34;的奇怪补贴。在分割行时,你必须为此编写自己的逻辑。