Home > Software design >  How to replace numbers with a string that are surrounded by double quotes in python?
How to replace numbers with a string that are surrounded by double quotes in python?

Time:03-30

I have a JSON string that looks like this

[{"25":"Fresh Vegetable Platter with Olive Oil Dip "},{"23":"Ginger-Lime Coconut Cake with Marshmallow Frosting "},{"26":"Mexican Pineapple Salad "},{"28":"Saut\u00e9ed Savoy Cabbage with Scallions and Garlic "},{"24":"Braised Escarole with Currants and Pine Nuts "}]

I want to replace the numbers with the word title but where the numbers in the "Saut\u00e9ed" part are causing a problem because I want to keep that that way.

I have tried:

recommendations = re.sub('\d', 'title', recommendations)

this gives me this:

[{"titletitle":"Fresh Vegetable Platter with Olive Oil Dip "},{"titletitle":"Ginger-Lime Coconut Cake with Marshmallow Frosting "},{"titletitle":"Mexican Pineapple Salad "},{"titletitle":"Saut\utitletitleetitleed Savoy Cabbage with Scallions and Garlic "},{"titletitle":"Braised Escarole with Currants and Pine Nuts "}]

CodePudding user response:

If you replace:

recommendations = re.sub('\d', 'title', recommendations)

with

recommendations = re.sub('\d ', 'title', recommendations)

it should work.

The tells the regex to match 'at least one (but possibly more) digits'.

For future reference in regex you can use these characters to indicate a specific number of occurrences to match:

  • ? 0 or 1 occurrences
  • 1 or more occurrences
  • * any number of occurrences (includes zero)

CodePudding user response:

Try with:

recommendations = re.sub(r'\d ','title', recommendations )

CodePudding user response:

Given you want "Saut\u00e9ed" not to be affected, here's a list comprehension for fun:

a = [{"25":"Fresh Vegetable Platter with Olive Oil Dip "},{"23":"Ginger-Lime Coconut Cake with Marshmallow Frosting "},{"26":"Mexican Pineapple Salad "},{"28":"Saut\u00e9ed Savoy Cabbage with Scallions and Garlic "},{"24":"Braised Escarole with Currants and Pine Nuts "}]

b = [{'title': list(i.values())[0]} for i in a]
  • Related