There are 3 ways to solve your problem
The most basic way:
list1 = ['mory','alphabet','fruit']
list2 = ['apple','banana','pear']
string = "There was a mory and the thing was a alphabet within the fruit. "
for i in range(len(list1)):
string = string.replace(list1[i], list2[i]
Here, i am just using for loop
in range of lenth of list1, and replacing the index i of list1 to index i of list2.
Using dictionary
list1 = ['mory','alphabet','fruit']
list2 = ['apple','banana','pear']
string = "There was a mory and the thing was a alphabet within the fruit. "
List_dict= {j:list2[i] for i,j in enumerate(list1)}
for i in list1:
string=string.replace(i, List_dict.get(i)
We have just read the elements of list1 and used enumerate
function to the index. Then we have used a dict
to associate element of list1 to element of list2. After that, we have used .replace
function to replace value of list1 to value of list2.
Using list:
list1 = ['mory','alphabet','fruit']
list2 = ['apple','banana','pear']
string = "There was a mory and the thing was a alphabet within the fruit. "
List_3= [j, list2[i] for i,j in enumerate (lists)]
for i in List_3:
String=string.replace(i[0],i[1])
The same consepts of dictionary method goes here, the difference is in first method we are using dictionary comprehension, you can use normal for loop
too to achieve it.
There are many more way to solve this problem, but the methods i have mentioned are the main or basic ones.