Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regular expression split function issue

I'm using python2 and I want to get rid of these empty strings in the output of the following python regular expression:

import re
x = "010101000110100001100001"
print re.split("([0-1]{8})", x)

and the output is this :

['', '01010100', '', '01101000', '', '01100001', '']

I just want to get this output:

['01010100', '01101000', '01100001']
like image 733
Ahmed Ramadan Avatar asked May 04 '26 01:05

Ahmed Ramadan


1 Answers

Regex probably isn't what you want to use in this case. It seems that you want to just split the string into groups of n (8) characters.

I poached an answer from this question.

def split_every(n, s):
    return [ s[i:i+n] for i in xrange(0, len(s), n) ]

split_every(8, "010101000110100001100001")
Out[2]: ['01010100', '01101000', '01100001']
like image 123
Tim Avatar answered May 06 '26 15:05

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!