What would be a more efficient approach to split a KLV string into lists/tuples of key, length, value as elements?
To add a little background, the first 3 digit make a key, next 2 indicates the length of value.
I have been able to solve the problem with the following code. But I don't think my code and logic is the most efficient way to do the task.
Therefore, I would love to hear other opinions so that I can get better.
result = []
def klv_split(ss):
while True:
group1 = ss[:3]
group2 = ss[3:5]
print(group2)
group3 = ss[5 : 5 + int(group2)]
result.append([group1, group2, group3])
try:
klv_split(ss[5 + int(group2) :])
except ValueError:
break
break
return result
klv_string = "0021571583400000026400412000000000200026047299049000850025003ADV25110Blahbleble25304677225400255002560204"
klv_split(klv_string)
print(result)
The expected output is a list of small ones with key-length-value as below.
[['002', '15', '715834000000264'], ['004', '12', '000000000200'], ['026', '04', '7299'], ['049', '00', ''], ['085', '00', ''], ['250', '03', 'ADV'], [
'251', '10', 'Blahbleble'], ['253', '04', '6772'], ['254', '00', ''], ['255', '00', ''], ['256', '02', '04']]