【问题标题】:Python - Divide a stringPython - 分割一个字符串
【发布时间】:2021-12-27 15:32:51
【问题描述】:

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

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[]

【问题讨论】:

  • 欢迎来到这里,您期望的确切输出是什么?您已经尝试过哪些代码?
  • 为什么字符串在a[ dancing而不是cat, [because处分割?
  • 因为字符串被分成了 before [ ] 和 after 所以的部分
  • 我希望有一个部分然后有一个 [跳舞棉花糖] 所以它的另一部分然后是猫然后是 [因为 iom 正在分裂我们的字符串]
  • 我希望像第二个 str 这样的输出是一个列表,

标签: python string split


【解决方案1】:

您可以使用此正则表达式模式查找所有匹配组,然后使用列表推导和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']

有用:

【讨论】:

    【解决方案2】:

    给你:

    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() 方法来实现所需的输出。

    请让我知道这是否有效。谢谢

    【讨论】:

    • 哦,我明白了,[] 应该是一个字符串。让我解决这个问题
    • 正是 [] 是字符串的一部分 :) 不是新列表
    • 我做了必要的更改。请立即查看
    • 谢谢哈哈,但我猜马蒂斯的解决方案对我来说更好:)
    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多