Python - 分割一个字符串

Python - Divide a string

您好,我想知道如何在出现 [ ] 时拆分字符串并将字符串转换为如下所示的列表:

str = "I wish to have a[dancing marshmellow]cat,[becase I am the]best loki joki ipock 进入:

str = ["I wish to have a","[dancing marshmellow]","cat,","[becase I am the]","best loki joki ipock"]

我试过使用 str.split("[") 但它没有正确划分它,因为我需要 [ 和 [ 之间的文本包含在输出 str[]

给你:

s="I wish to have a[dancing marshmellow]cat,[becase I am the]best loki joki ipock"
res = []
slowRunner = 0
for index in range(len(s)):
    if(s[index] == "["  and slowRunner != index-1):
        res.append(s[slowRunner:index])
        slowRunner = index
    elif(s[index] == "]" and s[index+1] != " "):
        res.append("["+s[slowRunner+1:index]+"]")
        slowRunner = index+1
    elif s[index] == "[":
        print(index)
        res.append(s[slowRunner:index])
        slowRunner = index
        
# Remaining string
if(slowRunner < len(s)-1):
    res.append(s[slowRunner:len(s)])
print(res)

输出

['I wish to have a', '[dancing marshmellow]', 'cat,', '[becase I am the]', 'best loki joki ipock']

注意:

如果这不是您所期望的,您可以使用 strip() 和 replace() 方法来实现所需的输出。

如果可行,请告诉我。谢谢

您可以使用此正则表达式模式查找所有匹配组,然后使用列表推导和 join 方法创建符合您预期形式的列表:

import re

string = "I wish to have a[dancing marshmellow]cat,[becase I am the]best loki joki ipock"
pattern = re.compile(r'(\[.*?\])|((?<=\]).*?(?=\[|$))|(^.*?(?=\[|$))')
lst = [''.join(s) for s in pattern.findall(string)]
print(lst)
# output
# ['I wish to have a', '[dancing marshmellow]', 'cat,', '[becase I am the]', 'best loki joki ipock']

有用: