Consider..
dict = { 'Спорт':'Досуг', 'russianA':'englishA' } s = 'Спорт russianA'
I'd like to replace all dict keys with their respective dict values in s
.
replace() function. The string class has a member function replace(to_be_replaced, replacement) and it replaces all the occurrences of substring “to_be_replaced” with “replacement” string. To replace all the multiple words in a string based on a dictionary.
replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.
replace() Return Value The replace() method returns a copy of the string where the old substring is replaced with the new substring. The original string is unchanged.
Replace a character in a string using for loop in python We can replace a character in a string with another character in python by using the replace() function or sub() function or a for loop.
Using re:
import re s = 'Спорт not russianA' d = { 'Спорт':'Досуг', 'russianA':'englishA' } pattern = re.compile(r'\b(' + '|'.join(d.keys()) + r')\b') result = pattern.sub(lambda x: d[x.group()], s) # Output: 'Досуг not englishA'
This will match whole words only. If you don't need that, use the pattern:
pattern = re.compile('|'.join(d.keys()))
Note that in this case you should sort the words descending by length if some of your dictionary entries are substrings of others.
You could use the reduce function:
reduce(lambda x, y: x.replace(y, dict[y]), dict, s)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With