MoreScratch
MoreScratch

Reputation: 3083

How to split a complex string in Python

Given the following string:

my_string = "fan_num=2,fan1=0,fan2=0,chain_xtime8={X0=8,X1=3,X2=11},chain_offside_6=0,chain_offside_7=0,chain_offside_8=0,chain_opencore_6=0,chain_opencore_7=0,chain_opencore_8=0"

How can I split it such that I get the following output:

[ 
  fan_num=2,
  fan1=0,
  fan2=0,
  chain_xtime8={X0=8,X1=3,X2=11},
  chain_offside_6=0,
  chain_offside_7=0,
  chain_offside_8=0,
  chain_opencore_6=0,
  chain_opencore_7=0,
  chain_opencore_8=0
]

I've tried:

output = my_string.split(',')

However, that splits the chain_xtime8 value which is not what I want. I am using Python 2.7.

Upvotes: 0

Views: 269

Answers (1)

Matt M
Matt M

Reputation: 710

Through a series of convoluted replacements, I converted this style into JSON. Then using json.loads you can convert it into a Python dict. This ASSUMES you do not use the characters being replaced and you continue only using integers as values

This can obviously be tightened up but I wanted to leave it readable

import json

my_string = "fan_num=2,fan1=0,fan2=0,chain_xtime8={X0=8,X1=3,X2=11},chain_offside_6=0,chain_offside_7=0,chain_offside_8=0,chain_opencore_6=0,chain_opencore_7=0,chain_opencore_8=0"

my_string = '{"' + my_string + '"}'
my_string = my_string.replace('=', '":"')
my_string = my_string.replace(',', '","')
my_string = my_string.replace('"{', '{"')
my_string = my_string.replace('}"', '"}')
myDict = json.loads(my_string)

pprint of myDict results :

{'chain_offside_6': '0',
 'chain_offside_7': '0',
 'chain_offside_8': '0',
 'chain_opencore_6': '0',
 'chain_opencore_7': '0',
 'chain_opencore_8': '0',
 'chain_xtime8': {'X0': '8', 'X1': '3', 'X2': '11'},
 'fan1': '0',
 'fan2': '0',
 'fan_num': '2'}

Also one more example -

print(myDict['chain_xtime8']['X0'])
>> 8

Upvotes: 2

Related Questions