使用 Python 将字符串解析为字典
Parsing a string to dict with Python
我有这样的字符串:
/acommand foo='bar' msg='Hello World!' -debugMode
或者像这样:
/acommand
foo='bar'
msg='Hello, World!'
-debugMode
如何将此字符串解析为字典和列表,如下所示:
{"command": "/acommand", "foo": "bar", "msg": "Hello World!"}
["-debugMode"]
我试过用string.split
解析,但好像不行。
argparse
好像是为命令行界面而生的所以不适用
如何使用 Python 实现此目的?谢谢!
你可以试试这样:
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']
我有这样的字符串:
/acommand foo='bar' msg='Hello World!' -debugMode
或者像这样:
/acommand
foo='bar'
msg='Hello, World!'
-debugMode
如何将此字符串解析为字典和列表,如下所示:
{"command": "/acommand", "foo": "bar", "msg": "Hello World!"}
["-debugMode"]
我试过用string.split
解析,但好像不行。
argparse
好像是为命令行界面而生的所以不适用
如何使用 Python 实现此目的?谢谢!
你可以试试这样:
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']