2017-02-25 42 views

回答

2

使用正則表達式

import re 

REGEX = r"([^=;]+)=([^=;]+)" 
finder = re.compile(REGEX) 

s = "column1=value1;column2=value2" 

matches = re.finditer(finder, s) 

d = {} 
for match in matches: 
    key = match.group(1) 
    val = match.group(2) 
    d[key] = val 

print(d) 

輸出:

{'column2': 'value2', 'column1': 'value1'} 
1

如果你真的想解析您的字符串成JSON你應該嘗試這樣的事:

import json # simplejson if you use a python version below 2.6 

string = u'{"column1":"value1", "column2": "value2"}' 
json = json.loads(string) 

如果你想把你的字符串解析成你應該嘗試使用的字典:

import ast 

string = u'{"column1":"value1", "column2": "value2"}' 
ast.literal_eval(string)=>{'column1': 'value1', 'column2': 'value2'} 
+0

這個問題的答案如何? – mpromonet

相關問題