Dan Ashton
Dan Ashton

Reputation: 21

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 "}]

Upvotes: 1

Views: 196

Answers (4)

Dan Ashton
Dan Ashton

Reputation: 21

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

this worked, this only replaces the numbers wrapped in ""

Upvotes: 0

PGHE
PGHE

Reputation: 1962

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]

Upvotes: 0

baileythegreen
baileythegreen

Reputation: 1194

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)

Upvotes: 1

Damini Suthar
Damini Suthar

Reputation: 1492

Try with:

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

Upvotes: 0

Related Questions