Home > database >  Parsing a string to dict with Python
Parsing a string to dict with Python

Time:11-09

I have a string like this:

/acommand foo='bar' msg='Hello World!' -debugMode

or like this:

/acommand
foo='bar'
msg='Hello, World!'
-debugMode

How can I parse this string to a dict and a list like this:

{"command": "/acommand", "foo": "bar", "msg": "Hello World!"}

["-debugMode"]

I've tried to use string.split to parse it but seems it's not feasible.

argparse seems like that it was born for the command line interface so it doesn't apply.

How to achieve this with Python? Thanks!

CodePudding user response:

you can try something like this:

s = "/acommand foo='bar' msg='Hello World!' -debugMode"
debug = [s.split(" ")[-1]]
s_ = "command="   ' '.join(s.split(" ")[:-1]).replace("'","")
d = dict(x.split("=") for x in s_.split(" ",2))
print (d)
print (debug)

{'command': '/acommand', 'foo': 'bar', 'msg': 'Hello World!'},

['-debugMode']

  • Related