gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:28:57 24 4
gpt4 key购买 nike

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

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

关于python - 通过python中的正则表达式替换特定字符串后面的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31894213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com