Home > Mobile >  Python - Divide a string
Python - Divide a string

Time:11-17

Hi I would like to know how I can split a string when a [ ] occur and turn the string into a list like the following :

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

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

I tried using str.split("[") But it didnt divide it correctly since i need the text in between both [ and [ to be included in the output str[]

CodePudding user response:

You can use this regex pattern to find all the matching groups and then use a list comprehension and join method to create a list that will be in your expected form:

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

Useful:

CodePudding user response:

Here you go:

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)

Output

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

NOTE:

If this is not what you're expecting, you may use strip() and replace() methods to achieve the desired output.

Do let me know if this works. Thanks

  • Related