How to change the string
to result
?
string = 'John and Mary are good friends'
d = {'John': 'Sam', 'Mary': 'Ann', 'are': 'are not'}
result = 'Sam and Ann are not good friends'
Thank you.
How to change the string
to result
?
string = 'John and Mary are good friends'
d = {'John': 'Sam', 'Mary': 'Ann', 'are': 'are not'}
result = 'Sam and Ann are not good friends'
Thank you.
If keys in dictionary have only one word is possible split, map by get
and join
back:
a = ' '.join(d.get(x, x) for x in string.split())
print (a)
Sam and Ann are not good friends
If possible multiple words and also is necessary use words boundaries for avoid replace substrings:
import re
string = 'John and Mary are good friends'
d = {'John and': 'Sam with', 'Mary': 'Ann', 'are good': 'are not'}
pat = '|'.join(r"\b{}\b".format(x) for x in d.keys())
a = re.sub(pat, lambda x: d.get(x.group(0)), string)
print (a)
Sam with Ann are not friends
You can do it like this:
string = 'John and Mary are good friends'
d = {'John': 'Sam', 'Mary': 'Ann', 'are': 'are not'}
result = string
for key, value in d.items():
result = result.replace(key, value)
print(result)
output:
Sam and Ann are not good friends
1 - Iterate over each word of string.
2 - check if word exists in dictionary keys.
3 - If it does exist append value of that word to result. if it does not, append word to result.
Basic approach:
string = 'John and Mary are good friends'
d = {'John': 'Sam', 'Mary': 'Ann', 'are': 'are not'}
s = string.split()
for i, el in enumerate(s):
if el in d:
s[i] = d[el]
print(' '.join(s))