Python Forum
loop for dynamic cut string - cleaner way?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
loop for dynamic cut string - cleaner way?
#1
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,
Reply
#2
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
Reply
#3
great
it's seem very clean now

but where does the "ID_tag" read take place?
I don't understand
Thanks ,
Reply
#4
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 := ?
Reply
#5
yes
I never seen\used this opertor before

Thanks ,
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I am trying to reverse a string using loop codinglearner 4 740 Sep-28-2021, 10:46 PM
Last Post: Pedroski55
  Create Dynamic For Loop quest 3 1,019 Apr-26-2021, 02:03 PM
Last Post: ibreeden
  cursor.execute: How to insert dynamic number in a string? stoeberhai 2 1,254 Mar-18-2021, 12:55 PM
Last Post: stoeberhai
  Convert string to JSON using a for loop PG_Breizh 3 1,212 Jan-08-2021, 06:10 PM
Last Post: PG_Breizh
  String slicing and loop iteration divyansh 9 2,576 Jun-07-2020, 10:29 PM
Last Post: divyansh
  Cleaner way to rewrite fakka 5 1,601 Dec-05-2019, 04:53 AM
Last Post: stullis
  Putting an array for each string that is printed to a loop ClaudioSimonetti 1 1,431 Feb-05-2019, 12:52 PM
Last Post: perfringo
  Dynamic Formatting of String mikera1979 2 1,817 Feb-27-2018, 07:09 AM
Last Post: mikera1979
  Is it possible to loop through class attributes via string? 04chiak 3 8,188 Feb-04-2018, 09:29 PM
Last Post: 04chiak
  Ending loop with string (capital & lowercase) MattWilk97 3 2,420 Oct-22-2017, 09:13 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020