Home > Net >  python split where there is bracket and replace
python split where there is bracket and replace

Time:11-15

I want to make substitutions to word in curly brackets. I have search some similar questions but they do not match what I want.

I have try to use regex. My though process is to first split the string where there is whitespace, then check each value in the splitted list and further split the value with the curly bracket. Then I will check if the value is in dict or not. Then I will replace if it is in the dict, if not I will add the other word. I am having difficulty getting it and I will appreciate assistance.

CodePudding user response:

Try:

import re

dicts = {"item1": "dog", "item2": "cat", "item4": "kindness"}

s = """This's my pet {item1|female donkey}. It was a gift from Mr {item3|David Smith}. Junior. I thank him for is {item4|humbleness}."""

pat = re.compile(r"\{([^|] )\|([^}] )}")
s = pat.sub(lambda g: dicts.get(g.group(1), g.group(2)), s)

print(s)

Prints:

This's my pet dog. It was a gift from Mr David Smith. Junior. I thank him for is kindness.

EDIT: In case where no default item is provided you can use:

import re

dicts = {"item1": "dog", "item2": "cat", "item4": "kindness"}

s = """This's my pet {item1|female donkey}. It was a gift from Mr {item3|}. Junior. I thank him for is {item4|humbleness}."""

pat = re.compile(r"\{([^|] )\|([^}]*)}")
s = pat.sub(lambda g: dicts.get(g.group(1), g.group(2).strip() or "N/A"), s)

print(s)

Prints:

This's my pet dog. It was a gift from Mr N/A. Junior. I thank him for is kindness.
  • Related