KoKlA
KoKlA

Reputation: 988

Replace the number which comes after a specific string via regular expression in python

I have a STRING which contains the following:

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

and I want to exchange the number of shares to 3 example:

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

I know I could do something like this:

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

But what I want is something like this:

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

Upvotes: 2

Views: 87

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180540

There are much better approaches than re but you can re.sub:

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

Output:

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

Or using json and use the 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"))

Upvotes: 2

Related Questions