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