使用re
库这应该是一项非常简单的任务。但是,我似乎无法将我的字符串拆分为分号]
和[
。在列表中没有分隔符的多个分隔符处分割
我已经阅读Splitting a string with multiple delimiters in Python,Python: Split string with multiple delimiters和Python: How to get multiple elements inside square brackets。
我的字符串:
data = "This is a string spanning over multiple lines.
At somepoint there will be square brackets.
[like this]
And then maybe some more text.
[And another text in square brackets]"
它应该返回:
['This is a string spanning over multiple lines.\nAt somepoint there will be square brackets.','like this', 'And then maybe some more text.', 'And another text in square brackets']
简单例子尝试:
data2 = 'A new string. [with brackets] another line [and a bracket]'
我想:
re.split(r'(\[|\])', data2)
re.split(r'([|])', data2)
但这些要么导致其在我的结果列表中的分隔符或错误列表干脆:前
['A new string.', 'with brackets', 'another line', 'and a bracket']
作为一个特殊的要求,所有的换行字符和空格:
['A new string. ', '[', 'with brackets', ']', ' another line ', '[', 'and a bracket', ']', '']
结果应该是并且在分隔符应该被移除并且不被包括在列表中。
是的,这比我推荐的非捕获组更简单。 –
工程很好。就像一个补充:我如何删除元素结尾/开始处的所有换行符和空格? – cherrun
好的。弄清楚了。在列表中的每个元素上使用'strip()'。再次感谢。 – cherrun