python-3.x 在每次出现包含该字符的字符之前拆分字符串

hujrc8aj  于 2023-01-22  发布在  Python
关注(0)|答案(3)|浏览(143)

基本上是这样的:
输入:

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

输出:

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

yxyvkwin1#

每次看到'0'时,请尝试以下操作:将tmp附加到result中,然后重置tmp

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

输出:

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

eni9jsuy2#

您可以使用正则表达式:

import re

s = "0101101000101011011110"

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

regex demo
或者:

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

regex demo
输出:

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

5n0oy7gb3#

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

相关问题