python - 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'
解决方案
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'
推荐阅读
- algorithm - sagemaker 的线性学习器可以用于多类分类吗?
- wordpress - 任何显示我网站上所有断开链接的 WordPress 插件?
- algorithm - 合并排序双向链表
- android - 无法使用 Volley 将数据从 android 发布到 api
- jquery - Flot 多折线图,其中类别不显示标签
- php - Laravel 5.6 Symfony \ Component \ Debug \ Exception \ FatalThrowableError(E_ERROR)类'\ App \ Utilisateurs'未找到
- angular - 如何在angular2中验证新密码并确认密码
- git - 如何修复:致命:无效的反向引用
- encryption - 低功耗蓝牙连接中的 LTK 是如何形成的?
- javascript - 在 iOS 浏览器中弹出带小数的数字小键盘