Replacing a substring (tag) in a given string in python based on dict

Question:

I am trying to replace inside a json text(which i transformed to string via json.dumps) one tag like {Prio}. This tag i append to the end of the string.

The strange thing is the tag {name} is replaced but the tag {Prio} is not.
Can anyone hint me on my problem with this topic, please. Would be nice!

#insert function
def insert_str(string, str_to_insert, index):
    return string[:index] + str_to_insert + string[index:]


#my demo json.dumps
text = "{hello this is just a test {name}, and i want to replace}"
#add a new replacement tag
text = insert_str(text,", {Prio}",len(text)-1)
print("String added at the end of text:")
print(text)

#create a key value pair dictionary
key_values = {"name": "John", "age": 30, "{Prio}": "New York"}
# show the dictionary
print("key_values: "+str(key_values))

for key, value in key_values.items():
    text = re.sub(f"{{{key}}}", str(value), text)
    print("")
    print(text)

Kind regards
Robert

Expected Result:
"{hello this is just a test {name}, and i want to replace, {Prio}}"
should end up in:

"{hello this is just a test John, and i want to replace, New York}"

The John is correctly filled in the New York not.

Note (background information):
If you ask yourself why i am do this. For the final JSON format this is needed (i fill in placeholder which i am trying to replace with additional JSON code afterwards). I am auto generating JIRA-tickets based on different inputs (doors db + project specific inputs).

Asked By: RoDae

||

Answers:

To do simple string replacement in Python, you can use str.replace:

>>> "hello mellow world".replace("ell", "X")
'hXo mXow world'

You are using re.sub which is a Regex replacement. This is adding complexity because { is meaningful in Regex and you need to escape them. But you’re not actually using any Regex patterns, so you’re getting this complexity with no benefit.

However, { is already supported by native Python string templating:

>>> "hello {who}!".format(who="world")
'hello world!'

You can use that instead to make your code simpler and easier to debug.

However, in your case, you are actually attempting to do replacements not just on any string, but on JSON. Manipulating raw JSON this way is a bad idea. Whitespace is not significant in JSON, and various formatting tools and even file encodings can throw your code off. You should instead parse the JSON to a dict with json.loads, then do your replacements on the keys and values of that dict, and produce the result with json.dumps.

Your question is probably getting downvoted (not by me) because:

  • The title is incorrect – you are not asking about doing replacemenets (which is already explained in other questions) but a very specific situation
  • The question is confusing – there is not clear example input and expected output
  • Your code is messy and hard to read, with a lot of stuff unrelated to the replacement
Answered By: Dommondke
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.