gpt4 book ai didi

python - 在列表中没有分隔符的情况下在多个分隔符处拆分

转载 作者:行者123 更新时间:2023-11-28 19:39:57 24 4
gpt4 key购买 nike

使用 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']

作为一项特殊要求,分隔符前后的所有换行符和空格都应删除,也不应包含在列表中。

最佳答案

>>> re.split(r'\[|\]', data2)
['A new string. ', 'with brackets', ' another line ', 'and a bracket', '']

关于python - 在列表中没有分隔符的情况下在多个分隔符处拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17049617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com