'How to replace numbers with a string that are surrounded by double quotes in python?
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 "}]
Solution 1:[1]
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)
Solution 2:[2]
Try with:
recommendations = re.sub(r'\d+','title', recommendations )
Solution 3:[3]
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]
Solution 4:[4]
recommendations = re.sub(r'"\d+"', '"title"', recommendations)
this worked, this only replaces the numbers wrapped in ""
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | baileythegreen |
| Solution 2 | Damini Suthar |
| Solution 3 | PGHE |
| Solution 4 | Dan Ashton |
