Python Split dynamic string to key value pairs

i need some help.
I have dynamic string like this:

S31
S4
S2M1L10XL8
S1M2L0XL0
S0M5L6XL8

and need change it to key value like:

{“S”:31}
{“S”:4}
{“S”:2, “M”:1, “L”:10, “XL”:8}
{“S”:1, “M”:2, “L”:0, “XL”:0}
{“S”:0, “M”:5, “L”:6, “XL”:8}

I try with

new_string = re.findall('(d+|[A-Za-z]+)', string)

but can’t find hoe to solve

Answer

Try this:

dict(re.findall('(D+)(d+)',your_string))
>>> s = "S2M1L10XL8"
>>> re.findall('(D+)(d+)',s)
[('S', '2'), ('M', '1'), ('L', '10'), ('XL', '8')]

1st Capturing Group (D+) D matches any character that’s not a digit (equivalent to [^0-9])

  • matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)

2nd Capturing Group (d+) d matches a digit (equivalent to [0-9])

  • matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)

https://regex101.com/r/hww2rm/1