Home > Mobile >  Split string before every occurrence of a character including that character
Split string before every occurrence of a character including that character

Time:01-21

Basically something like this:

Input:

"0101101000101011011110" #0 is the character we are splitting after

Output:

["0", "10", "110", "10", "0", "0", "10", "10", "110", "11110"]

CodePudding user response:

Try something like below, every time see '0' append tmp in result then reset tmp:

s = "0101101000101011011110"
res = []
tmp = ''
for c in s:
    tmp  = c
    if c == '0':
        res.append(tmp)
        tmp = ''
print(res)

Output:

['0', '10', '110', '10', '0', '0', '10', '10', '110', '11110']

CodePudding user response:

You can use a regex:

import re

s = "0101101000101011011110"

out = re.findall('(1*0|1 0?)', s)

regex demo

Or:

out = re.split('(?<=0)(?=.)', s)

regex demo

Output:

['0', '10', '110', '10', '0', '0', '10', '10', '110', '11110']

CodePudding user response:

x = str1.split("0")
output = [ "0" i for i in x]
  • Related