[Tutor] How to split string into separate lines

Alan Gauld alan.gauld at btinternet.com
Wed Dec 3 23:31:12 CET 2014

On 03/12/14 18:18, shweta kaushik wrote:

> I need help for doing this task. I know it will be simple but I am not
> able to do it.

Your description of the task is not very precise so I'll
make some guesses below.

> output_message_packet= fe01b84100000000000000002756fe02fe01b94100000....
> I want to split this into separate message packets like this:
> fe01b84100000000000000002756fe02
> fe01b94100000000000000006239fe02

It looks like the packet terminator is either fe02 or a fixed length 
record. It's not clear whether the fixed length is accidental or 
deliberate or whether its the terminator that is coincidentally the 
same. I'm guessing its probably based on terminator...

To split by 'fe02' just use string split then add the separator
back on:

sep = 'fe02'
packets = [pkt+sep for pkt in data.split(sep)]

If it is based on length it will look something like:

data = []
while s:
    s = s[length:]

> After this I want to split this into bytes:
> fe 01 b8 41 00 00 00 00 00 00 00 00 27 56 fe 02

This is the same split by length problem applied to
each packet with length 2.

In fact if it is split by length in both you could write
a helper function:

def split_by_length(s,length):
     data = []
     while s:
         s = s[length:]
     return data

And call it with

packets = split_by_length(inputData, packetLength)
bytes = [split_by_length(p,2) for p in packets]

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list