Python String - Replace from dictionary


Python String - Replace from dictionary

To replace substrings in a Python string based on a dictionary mapping, you can use a simple loop like a For loop.

In this tutorial, we shall see the step by step process to replace substrings in a string based on a dictionary using For loop, with examples.

1. Replace substrings in a string based a dictionary using For loop in Python

Given a string in x, and mappings in a dictionary. We have to use the mappings in dictionary to replace old substring with new values in string x using For loop.

Steps

  1. Given string in x.
x = "I have an apple and a dog. The apple is red, and the dog is brown."
  1. Given dictionary mapping in replacement_dict. The keys are old substrings, and the respective values are the new replacement substrings.
replacement_dict = {
    'apple': 'fruit',
    'carrot': 'vegetable',
    'dog': 'animal'
}
  1. Use Python For loop to iterate over each entry in the dictionary replacement_dict, and replace the old substring(key in item) with the new substring(value in item). The replace operation is done using string replace() method.
for old_str, new_str in replacement_dict.items():
    x = x.replace(old_str, new_str)

Program

The complete program to replace substrings in a Python string based on a dictionary mapping using For loop is given below.

Python Program

# Define a dictionary to map substrings to their replacements
replacement_dict = {
    'apple': 'fruit',
    'carrot': 'vegetable',
    'dog': 'animal'
}

# Your input string
x = "I have an apple and a dog. The apple is red, and the dog is brown."

# Replace substrings based on the dictionary
for old_str, new_str in replacement_dict.items():
    x = x.replace(old_str, new_str)

# Print the modified string
print(x)

Output

I have an fruit and a animal. The fruit is red, and the animal is brown.

Summary

In this Python Strings tutorial, we learned how to replace substrings in a string based on a dictionary using For loop, with examples.