2

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
1
  • You could treat the whole object as JSON, parse it to Python, set the value in the resulting dictionary, convert back to JSON and re-compose the line.. It'd be more robust, I'd wager. Commented Aug 8, 2015 at 14:42

1 Answer 1

2

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"))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.