首页 > 解决方案 > 如何在包含冒号的单词之前插入换行符

问题描述

我有一个全是一行的字符串,例如:

Breed: Pembroke Welsh Corgi Price: $2,200 Gender: Female Nickname: Koko 
Age: 9 Weeks Old Color/Markings: yellow and white Size at Maturity: 
Medium Availability Date: 09/30/2018 Shipping Area: Worldwide Payment 
Method: Money Order/Cashier's Check, Paypal, Credit Cards, Cash

我希望输出是:

Breed: Pembroke Welsh Corgi
Price: $2,200
Gender: Female
Nickname: Koko

等等等等。基本上\n在以冒号结尾的新类别之前插入一个。

感谢您提前回复!

标签: pythonstringpython-3.xsplitnewline

解决方案


为什么没有人提出正则表达式解决方案?:)

import re
txt = '''your text'''
re.sub(r'(\w+):', r'\n\1:', txt).strip()

如果 original 中有换行符txt,您最终可能会在输出中出现双换行符。它们可以很容易地删除:

re.sub(r'\n\n', r'\n', # Remove double line breaks
       re.sub(r'(\w+):',r'\n\1:',txt).strip())

此解决方案假定冒号前只有一个感兴趣的单词。事实上,可能无法决定如何拆分“Shipping Area: Worldwide Payment Method: Money”。是“收货地区:全球”和“付款方式:金钱”还是“收货地区:全球付款”和“方法:金钱”?


推荐阅读