Skip to main content
 首页 » 编程设计

python之通过python中的正则表达式替换特定字符串后面的数字

2024年10月24日27lovecherry

我有一个包含以下内容的字符串:

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

我想将股票数量交换为 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 

请您参考如下方法:

有比 re 更好的方法,但你可以 re.sub:

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

输出:

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

或者使用 json 并使用 key :

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"))