Python Forum
loop for dynamic cut string - cleaner way? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: loop for dynamic cut string - cleaner way? (/thread-35610.html)



loop for dynamic cut string - cleaner way? - korenron - Nov-22-2021

hello ,
I have a long string of data the (80211 frame - if its help) and I want to cut it to pieces according to this logic:
first byte is the TAG
second byte is the lenght
then data length is acoording to the second byte

this is what I have done , is there a way yo make it cleaner?
IE_Data= 010402040b1632080102030405060708
start = 0
BYTE_SIZE = 2

for i in range(start, len(IE_Data)):
    Tag_ID = IE_Data[start:start + BYTE_SIZE]
    length = IE_Data[start + BYTE_SIZE: start + BYTE_SIZE + BYTE_SIZE]
    length_int = int(length,16)*2
    data = IE_Data[start+4:start+4+length_int]
    data_length = len(data)
    start = start + 4 + data_length
    print(
        "id - " + Tag_ID,
        "\n\rlength - " + length,
        "\n\rdata - " + data
    )
)
Thanks,


RE: loop for dynamic cut string - cleaner way? - Gribouillis - Nov-22-2021

This version perhaps?
import io

IE_Data= "010402040b1632080102030405060708"
BYTE_SIZE = 2

ifh = io.StringIO(IE_Data)
while tag_id := ifh.read(BYTE_SIZE):
    length = ifh.read(BYTE_SIZE)
    data = ifh.read(BYTE_SIZE * int(length, 16))
    print(f"id - {tag_id}\n\rlength - {length}\n\rdata - {data}")
Output:
id - 01 length - 04 data - 02040b16 id - 32 length - 08 data - 0102030405060708



RE: loop for dynamic cut string - cleaner way? - korenron - Nov-22-2021

great
it's seem very clean now

but where does the "ID_tag" read take place?
I don't understand
Thanks ,


RE: loop for dynamic cut string - cleaner way? - Gribouillis - Nov-22-2021

There are three calls to ifh.read() in this code. The first call reads the ID tag, the second call reads the length and the third call reads the data. Perhaps you need to learn about Python 3.8's walrus operator := ?


RE: loop for dynamic cut string - cleaner way? - korenron - Nov-22-2021

yes
I never seen\used this opertor before

Thanks ,