我有一个包含许多行的文本。你知道吗
我想根据以特定字符结尾的字符串来拆分它。你知道吗
例如: 我的文本包含以下数据
Hi
I'm here:
London
UK
USA
Where are you:
here
there
what will you do:
something
somethin2
我要将此文本拆分为一个列表,其中分隔符作为以结尾的字符串
冒号-:
在这种情况下,最终结果列表将是
[ Hi, London UK USA, here there, something somethin2 ]
在python中如何做到这一点?你知道吗
我知道我们可以用一个单独的字符或一些其他的字符串来分隔。但在这种情况下该怎么办呢?你知道吗
下面是一个如何做到这一点的小例子。你知道吗
注意:比@Ajax1234的答案更容易理解,但效率要低得多。你知道吗
输出:
可以使用正则表达式拆分:
正则表达式
^.*:$
查找以:
结尾的整行Demo
和
re.splits
分割该模式上的字符串并删除分隔线。然后在每个字符串块中用' '
替换\n
,就得到了所需的输出。你知道吗您可以使用
itertools.groupby
:输出:
相关问题 更多 >
编程相关推荐