首页 > 解决方案 > python - 如何在python中每个字符串的第n个分隔符添加一个新行?

问题描述

我正在尝试为字符串中的每个第 n 个分隔符添加一个新行。

例如,我将每 3 个 '|' 添加一个新行 在下面的字符串中:

nthelement = 3
delimiter = '|'
string = 'AB|CD|EEEE|GGg|gger342|gff534|gre343|FGS'
#splitter here
output = 'AB|CD|EEEE|\nGGg|gger342|gff534|\ngre343|FGS'

标签: python

解决方案


Found a couple solutions but this is the cleanest I've come up with so far:

items = string.split(delimiter)
groups = []


while items:
    first_three, items = items[:nthelement], items[nthelement:]
    groups.append(first_three)


result = "|\n".join("|".join(g) for g in groups)

Output:

>>> result
'AB|CD|EEEE|\nGGg|gger342|gff534|\ngre343|FGS'

推荐阅读