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

Patricia Arquette
Release: 2024-10-19 16:03:30
Original
162 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!