Python - Specific case change in String List
Last Updated :
18 May, 2023
While working with String lists, the problem of cases is common, but sometimes, we are concerned about changing cases in strings selectively. i.e. on the basis of another list. This can have applications in day-day programming. Let us discuss certain ways in which this task can be performed.
Method #1 : Using loop + upper() + enumerate()
This is one of the ways in which this task can be performed. In this, we run a loop for each element and compare strings, if found equal, then cases of those lists don't change, and the rest strings cases are changed.
Python3
# Python3 code to demonstrate
# Specific case change in String List
# using loop + upper() + enumerate()
# Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
# Printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Specific case change in String List
# using loop + upper() + enumerate()
for idx, ele in enumerate(test_list1):
for ele2 in test_list2:
if ele == ele2.upper():
test_list1[idx] = ele2
# Printing result
print("The string list after case change is : " + str(test_list1))
Output : The original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2: Using loop + capitalize()
This method performs similarly to the above one, the difference being that instead of upper(), capitalize() is used to perform the task of changing cases.
Python3
# Python3 code to demonstrate
# Specific case change in String List
# using loop + capitalize()
# Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
# Printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Specific case change in String List
# using loop + capitalize()
for idx, ele in enumerate(test_list1):
if ele.capitalize() in test_list2:
test_list1[idx] = ele.capitalize()
# Printing result
print("The string list after case change is : " + str(test_list1))
Output : The original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']
Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.
Method 3: Using List Comprehension
This method uses a list comprehension to change the cases of the elements in the first list based on the second list.
Python3
#Python3 code to demonstrate
#Specific case change in String List
#using List Comprehension
#Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
#printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
#Specific case change in String List
#using List Comprehension
test_list1 = [x.capitalize() if x.capitalize() in test_list2 else x for x in test_list1]
#printing result
print ("The string list after case change is : " + str(test_list1))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']
Time Complexity: O(n), where n is the length of test_list1
Auxiliary Space: O(n), as a new list is created.
Explanation: The list comprehension iterates through each element in test_list1 and checks if the capitalized version of the element is present in test_list2. If it is, it replaces the element in test_list1 with the capitalized version, otherwise it remains unchanged.
Method #4: Using the map() function and ternary operator:
The map() function in Python can be used to apply a given function to each element of a list. We can use the ternary operator to check if the element is present in the second list and then apply the necessary case change operation.
Steps:
- Define the two lists to be processed.
- Define a lambda function that checks if an element is present in the second list and applies the necessary case change operation.
- Use the map() function to apply the lambda function to each element of the first list.
- Convert the result of the map() function back to a list.
- Print the final result.
Python3
# Python code to demonstrate
# Specific case change in String List
# using map() function and ternary operator
# Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# define lambda function for case change
def case_change(x): return x.capitalize(
) if x.capitalize() in test_list2 else x
# Applying lambda function to each element
# of first list using map()
test_list1 = list(map(case_change, test_list1))
# Printing the final result
print("The string list after case change is : " + str(test_list1))
OutputThe original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']
Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(n), where n is the length of the list (due to the creation of a new list in the map() function).
Method#5:using dictionary comprehension
step-by-step algorithm for the approach
Step 1: Initialize test_list1 and test_list2.
Step 2: Create an empty dictionary replace_dict.
Step 3: Iterate over each element in test_list1 and test_list2 using a nested loop.
Step 4: For each element in test_list1, convert it to uppercase and compare it to each element in test_list2 that has also been converted to uppercase.
Step 5: If a match is found, add a key-value pair to replace_dict where the key is the uppercase version of the element in test_list1 and the value is the corresponding element from test_list2.
Step 6: Use a list comprehension to create a new test_list1 by iterating through each element in the original test_list1.
Step 7: For each element, use the get() method to check if it exists in replace_dict. If it does, use the corresponding value from replace_dict. Otherwise, use the original element.
Step 8: Print the modified test_list1.
Python3
# Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
# Printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Specific case change in String List using dictionary comprehension
replace_dict = {ele.upper(
): ele2 for ele in test_list1 for ele2 in test_list2 if ele.upper() == ele2.upper()}
test_list1 = [replace_dict.get(ele.upper(), ele) for ele in test_list1]
# Printing result
print("The string list after case change is : " + str(test_list1))
OutputThe original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']
Time complexity: O(n^2)
Auxiliary space: O(min(n, m) + n).
Similar Reads
Add Substring at Specific Index Python In Python, String is an immutable datatype, what this means is, that there are lot many restrictions when one handles its manipulation. The problem of adding something at a position at string is not possible, without the list reconstruction. Let's discuss certain ways in which this task can be perfo
6 min read
Create a List of Strings in Python Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
3 min read
Python | Case Counter in String Sometimes, while working with Python String, we can have a problem in which we need to separate the lower and upper case count. This kind of operation can have its application in many domains. Let's discuss certain ways in which this task can be done. Method #1: Using map() + sum() + isupper() + isl
7 min read
Python | Convert string list into multiple cases Sometimes, while working with Python strings, we might have a problem in which we have list of strings and we wish to convert them into specified cases. This problem generally occurs in the cases in which the strings we receive are ill-cased. Let's discuss certain ways in which this task can be perf
4 min read
Python - Filter Similar Case Strings Given the Strings list, the task is to write a Python program to filter all the strings which have a similar case, either upper or lower. Examples: Input : test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"]Â Output : ['GFG', 'best', 'all', 'GEEKS']Â Explanation : GFG is all uppercase, best is
9 min read
Remove Character in a String at a Specific Index in Python Removing a character from a string at a specific index is a common task when working with strings and because strings in Python are immutable we need to create a new string without the character at the specified index. String slicing is the simplest and most efficient way to remove a character at a
2 min read
Python - Case Insensitive string counter Given a list of strings, find the frequency of strings case insensitive. Input : test_list = ["Gfg", "Best", "GFG", "is", "IS", "BEST"] Output : {'gfg': 2, 'best': 2, 'is': 2} Explanation : All occur twice. Input : test_list = ["Gfg", "gfg", "GFG"] Output : {'gfg': 3} Explanation : Only "gfg" 3 occu
4 min read
Case-insensitive string comparison in Python The goal here is to compare strings in a list without considering their case, meaning the comparison should ignore whether letters are uppercase or lowercase. For example, given the list ["hello", "HELLO", "HeLLo"], we want to check if all strings are equal, ignoring the case. Let's explore differen
2 min read
Reverse All Strings in String List in Python We are given a list of strings and our task is to reverse each string in the list while keeping the order of the list itself unchanged. For example, if we have a list like this: ['gfg', 'is', 'best'] then the output will be ['gfg', 'si', 'tseb'].Using For LoopWe can use a for loop to iterate over th
2 min read
Python | Grouping similar substrings in list Sometimes we have an application in which we require to group common prefix strings into one such that further processing can be done according to the grouping. This type of grouping is useful in the cases of Machine Learning and Web Development. Let's discuss certain ways in which this can be done.
7 min read