Home  >  Article  >  Backend Development  >  How to Perform Efficient String Replacements Using a Dictionary in Python?

How to Perform Efficient String Replacements Using a Dictionary in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-19 16:03:30164browse

How to Perform Efficient String Replacements Using a Dictionary in Python?

How to Perform Multiple String Replacements Using a Dictionary

In scenarios where you need to make multiple replacements within a string based on key-value pairs, utilizing a dictionary can prove effective. Here's a Python solution:

<code class="python">import re

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

# Construct a regular expression pattern for all dictionary keys
keys = (re.escape(k) for k in d.keys())
pattern = re.compile(r'\b(' + '|'.join(keys) + r')\b')

# Replace keys with corresponding values
result = pattern.sub(lambda x: d[x.group()], s)
# Output: 'Досуг englishA'</code>

This approach uses regular expressions to locate the keys in the string and substitutes them with their values from the dictionary. To match only whole words, specify word boundaries (b) in the pattern.

If matching whole words is not required, use the pattern:

<code class="python">pattern = re.compile('|'.join(re.escape(k) for k in d.keys()))</code>

Note: In this case, sort the dictionary keys descending by length to prevent erroneous replacements when some keys are substrings of others.

The above is the detailed content of How to Perform Efficient String Replacements Using a Dictionary in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn