2015-08-08 25 views
2

數我有包含以下替換經由正則表達式的特定字符串之後進來蟒

tesla = {"number_of_shares":0, "avg_price":200} 

一個STRING和我wan't交換股數到3的例子中:

tesla = {"number_of_shares":3, "avg_price":200} 

我知道我可以做這樣的事情:

string = r'tesla = {"number_of_shares":0, "avg_price":200}' 
new_string = string.split(":")[0] + ":3" + "," + string.split(",",1)[1] 

但我想是一樣的東西這樣的:

string = r'tesla = {"number_of_shares":0, "avg_price":200}' 
replace_function(string_before_number=r'tesla = {"number_of_shares":}', string) # replace the number which comes after r'"number_of_shares":' with 3 
+0

您可以將整個對象視爲JSON,將其解析爲Python,設置v在生成的字典中找到答案,將其轉換回JSON並重新編寫該行。它會更強大,我會下注。 –

回答

2

還有比重新好得多的辦法,但你可以應用re.sub:

import re 
print(re.sub('(?<="number_of_shares":)\d+?',"3",string)) 

輸出:

tesla = {"number_of_shares":3, "avg_price":200} 

或者使用JSON和使用關鍵:

import json 

def parse_s(s, k, repl): 
    name, d = s.split("=", 1) 
    js = json.loads(d) 
    js[k] = repl 
    return "{} = {}".format(name, str(js)) 


print(parse_s(string, "number_of_shares", "3"))