In this Python tutorial, we will learn to find and replace string values in a list in Python.
Table Of Contents
Suppose we have a list of strings,
grocery_list = ['Bread','Egg','Milk']
In this list, we want to change the quantity of 6 eggs with the 12 eggs. The final string should be like,
grocery_list = ['Bread','Egg','Milk']
Now we will learn about some methods though which we can do this.
Method 1 : Using List comprehension and replace() method
First method that we will be using is a combination of List Comprehension and replace() method.
What is List Comprehension?
List Comprehension is a shorter syntax of creating a new list or updating a list based on certain criteria.
What is the replace() method?
The replace() method of class string, is used to replace an element with a new element. It recieves three parameters :
- old : Old value which you want to replace
- new : New value which you want to replace
- count : Optional. How many occurrence of old value you want to replace. By default it replaces all occurrences.
Now we will find and replace string values in a list using the list comprehension and the replace() method. See the example code below :
# initialized a list with grocery items # and string values of items. grocery_list = ['Bread', 'Egg', 'Milk'] # type() will print the type of var grocery_list # which happens to be of class list. print(type(grocery_list)) # Using List Comprehension and replace() method # to replace string values in a list grocery_list = [items.replace('', '') for items in grocery_list] print(grocery_list)
<class 'list'> ['Bread', 'Egg', 'Milk']
In the above example code and output, we have successfully replaced the string value of egg (which was 6 earlier) to 12 with the comination of List Comprehension and replace() method. Using for Loop in the List Comprehension, we iterated through the list items and then replace() method has been used to find and replace string value of egg. Then through the List Comprehension we builded a new list of strings with updated contents.
Method 2 : Using lambda() and map() function
Next method that we will be using to find and replace string values in a list, is the combination of map(), lambda() and replace() functions.
What are map() and Lambda function ?
map() : The map() method accepts a sequence and a function as arguments. Then it appplies the given function to each element in the sequence like list, tuple etc, and returns a new sequence containing the results.
Lambda Function : Normal functions have name, and they are defined using the def keyword. But lambda functions do not have names.They are defined using the lambda keyword and are built at execution time. A Lambda function can take any number of arguments but can return only one value.
See the example code below of this method then we will discuss about this.
# initialized result list with marks of subjects result = ['Science', 'English', 'Maths'] # Lambda function, that accepts a string as argument and # replaces contents in that string lambdaFunc = lambda st : str.replace(st, 'Science', 'Science') # Replacing string values using map() anad the lambda functions new_result = list(map(lambdaFunc, result)) print(new_result)
<class 'list'> ['Science', 'English', 'Maths']
In above code and example, using Lambda function and map() function we have successfully replaced the string value of Science in the list. Here, map() function will iterate over the items of list results and apply given lambda function on each of the item. This lambda function will call the repalce() function to find the given substring and then replace it with the new substring. The map() function will return a sequence of values returned by the lambda functions, then we again casted it back to a list.
Method 3 : Using while loop
Next method that we will be using to find and replace string values in a list in Python is by using a loop. Here, we will be using a while loop, although you can always use other looping methods like for loop. See the example code below
# initailized a list with name and scores as string value score = ['Rahul','Rohit','Kohli'] # type() will print the data type of var score # which happens to be of class list print(type(score)) i = 0 while i < len(score): # finding string value if score[i] == 'Kohli': # repalcing string value score[i] = 'Kohli' i += 1 print(score)
<class 'list'> ['Rahul', 'Rohit', 'Kohli']
In the example, we have used a while loop to iterate over the items of list. During the loop, we looked for the string value using the if the statement, and then repalced the matched string value with desired value.
So in this python tutorial to find and replace string values in a list, we learned about four different methods through which we can replace string values. You can always use all the methods according to your use but the easiest to read and understand is the first method in which we have used combination of List Comprehension and replace() method, which has shorter syntax and better understanding. Third method(map() + lambda()) can also be very useful but it has performance issues.
Also i have used Python 3.10.1 for writing examples. Type python –version to check your python version. Always try to write & understand example codes. Happy Coding.