Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to replace a string using a dictionary of replacements?

Tags:

python

regex

Consider..

dict = { 'Спорт':'Досуг', 'russianA':'englishA' }  s = 'Спорт russianA' 

I'd like to replace all dict keys with their respective dict values in s.

like image 256
meder omuraliev Avatar asked Mar 08 '10 10:03

meder omuraliev


People also ask

How do you replace a string in a dictionary?

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.

How do you replace a specific part of a string with something else Python?

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.

Which method can be used to replace parts of a string?

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.

How do you replace a word in a string with a loop in Python?

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.


2 Answers

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.

like image 177
Max Shawabkeh Avatar answered Oct 13 '22 05:10

Max Shawabkeh


You could use the reduce function:

reduce(lambda x, y: x.replace(y, dict[y]), dict, s) 
like image 23
codeape Avatar answered Oct 13 '22 06:10

codeape