[Tutor] how to split a stream of chars

Alan Gauld alan.gauld at btinternet.com
Mon Apr 9 19:03:01 CEST 2007


<emilia12 at mail.bg> wrote 
> i have a long stream of data, represented in hexadecimal
> form. I need to split it in bytes (by 2 chars each). eg
> '00010203040506'... -> ['00', '01, '02' ...].

> So my question is: is there an inverse function of zip, or
> an easy way to split this long string in pairs (without
> indexing in cycle, nor regexpr.)?

I'm not quite sure what you mean by 'indexing in cycle' 
but you will need some kind of loop to extract this data
whether explicit or hidden inside a library function.

My guess is the simplest solution is to use list slicing 
and a list comprehension with a step size of 2. 
Something like:

bytes = [stream[start :start+2] for start in range(0,len(stream),2)]

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
     



More information about the Tutor mailing list