Python – Remove similar index elements in Strings
Last Updated :
18 Apr, 2023
Given two strings, removed all elements from both, which are the same at similar index.
Input : test_str1 = ‘geels’, test_str2 = ‘beaks’
Output : gel, bak
Explanation : e and s are removed as occur in same indices.
Input : test_str1 = ‘geeks’, test_str2 = ‘geeks’
Output : ”, ”
Explanation : Same strings, all same index, hence removed.
Method #1 : Using loop + zip() + join()
In this, we pair elements with its index using join(), and check for inequality to filter only dissimilar elements in both strings, join() is used to convert result in strings.
Python3
test_str1 = 'geeks'
test_str2 = 'beaks'
print ( "The original string 1 is : " + str (test_str1))
print ( "The original string 2 is : " + str (test_str2))
list1 = list (test_str1)
list2 = list (test_str2)
res1 = []
res2 = []
for ch1, ch2 in zip (list1, list2):
if ch1 ! = ch2:
res1.append(ch1)
res2.append(ch2)
res1 = "".join(res1)
res2 = "".join(res2)
print ( "Modified String 1 : " + str (res1))
print ( "Modified String 2 : " + str (res2))
|
Output
The original string 1 is : geeks
The original string 2 is : beaks
Modified String 1 : ge
Modified String 2 : ba
Method #2: Using list comprehension
Performs task using similar method as above, just one-liner to perform task in compact form.
Python3
test_str1 = 'geeks'
test_str2 = 'beaks'
print ( "The original string 1 is : " + str (test_str1))
print ( "The original string 2 is : " + str (test_str2))
res = ["".join(mastr) for mastr
in zip ( * [(a, b) for a, b in zip (test_str1, test_str2) if a ! = b])]
print ( "Modified String 1 : " + str (res[ 0 ]))
print ( "Modified String 2 : " + str (res[ 1 ]))
|
Output
The original string 1 is : geeks
The original string 2 is : beaks
Modified String 1 : ge
Modified String 2 : ba
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using index() and replace() methods
Python3
test_str1 = 'geeks'
test_str2 = 'beaks'
print ( "The original string 1 is : " + str (test_str1))
print ( "The original string 2 is : " + str (test_str2))
for i in test_str1:
if i in test_str2:
if (test_str1.index(i) = = test_str2.index(i)):
test_str1 = test_str1.replace(i,"", 1 )
test_str2 = test_str2.replace(i,"", 1 )
print ( "Modified String 1 : " + str (test_str1))
print ( "Modified String 2 : " + str (test_str2))
|
Output
The original string 1 is : geeks
The original string 2 is : beaks
Modified String 1 : ge
Modified String 2 : ba
Method #4: Using enumerate() function
Step-by-step approach:
- Initialize the two given strings.
- Iterate through the characters of the strings using enumerate() and list comprehension.
- For each character, compare it with the character at the corresponding index in the other string.
- If they are not equal, add the character to a list.
- Join the characters in the list to form the modified strings.
- Print the modified strings.
Below is the implementation of the above approach:
Python3
test_str1 = 'geeks'
test_str2 = 'beaks'
print ( "The original string 1 is : " + str (test_str1))
print ( "The original string 2 is : " + str (test_str2))
res1 = ''.join(])
res2 = ''.join(])
print ( "Modified String 1 : " + str (res1))
print ( "Modified String 2 : " + str (res2))
|
Output
The original string 1 is : geeks
The original string 2 is : beaks
Modified String 1 : ge
Modified String 2 : ba
Time Complexity: O(n), where n is the length of the strings.
Auxiliary Space: O(n), where n is the length of the strings.
Method #5: Using map() + lambda function + zip() + join()
Step-by-step approach:
- Initialize two strings test_str1 and test_str2
- Create two lists list1 and list2 by using the map() function to apply a lambda function
- Zip the two lists list1 and list2 together using zip() to get a list of tuples
- Use another map() function to apply a lambda function to each tuple in the zipped list
- Join the resulting list of characters from the previous step using the join() function to get the modified strings.
- Print the modified strings.
Below is the implementation of the above approach:
Python3
test_str1 = 'geeks'
test_str2 = 'beaks'
print ( "The original string 1 is : " + str (test_str1))
print ( "The original string 2 is : " + str (test_str2))
res1 = ' '.join(list(map(lambda i, j: i if i != j else ' ', test_str1, test_str2)))
res2 = ' '.join(list(map(lambda i, j: i if i != j else ' ', test_str2, test_str1)))
print ( "Modified String 1 : " + str (res1))
print ( "Modified String 2 : " + str (res2))
|
Output
The original string 1 is : geeks
The original string 2 is : beaks
Modified String 1 : ge
Modified String 2 : ba
The time complexity of this approach is O(n), where n is the length of the input strings.
The auxiliary space is also O(n), since we create a new string of length n to store the result.
Method 6: use the built-in filter() function.
Step-by-step approach:
- Initialize an empty string to store the result.
- Use the filter() function to create a filter object that only keeps characters that are not similar in index in both strings.
- Use the join() function to convert the filtered object into a string.
Below is the implementation of the above approach:
Python3
test_str1 = 'geeks'
test_str2 = 'beaks'
print ( "The original string 1 is : " + str (test_str1))
print ( "The original string 2 is : " + str (test_str2))
filter_obj1 = filter ( lambda x: x[ 0 ] ! = x[ 1 ], zip (test_str1, test_str2))
filter_obj2 = filter ( lambda x: x[ 0 ] ! = x[ 1 ], zip (test_str2, test_str1))
res1 = ''.join([x[ 0 ] for x in filter_obj1])
res2 = ''.join([x[ 0 ] for x in filter_obj2])
print ( "Modified String 1 : " + str (res1))
print ( "Modified String 2 : " + str (res2))
|
Output
The original string 1 is : geeks
The original string 2 is : beaks
Modified String 1 : ge
Modified String 2 : ba
Time complexity: O(n), where n is the length of the strings.
Auxiliary space: O(n), where n is the length of the strings, because we create a temporary list to store the filtered elements before joining them into a string.
Similar Reads
Python | Extract similar index elements
Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are having similar index values. This kind of problem can come in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loo
6 min read
Python - Check Similar elements in Matrix rows
Given a Matrix and list, the task is to write a Python program to check if all the matrix elements of the row are similar to the ith index of the List. Input : test_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Output : True Explanation : All rows have same elements.Input : test_list = [[1, 1,
8 min read
Swap elements in String list - Python
Swapping elements in a string list means we need to exchange one element with another throughout the entire string list in Python. This can be done using various methods, such as using replace(), string functions, regular expressions (Regex), etc. For example, consider the original list: ['Gfg', 'is
3 min read
Similarity Metrics of Strings - Python
In Python, we often need to measure the similarity between two strings. For example, consider the strings "geeks" and "geeky" âwe might want to know how closely they match, whether for tasks like comparing user inputs or finding duplicate entries. Let's explore different methods to compute string si
3 min read
Python | Kth index character similar Strings
Sometimes, we require to get the words that have the Kth index with the specific letter. This kind of use case is quiet common in places of common programming projects or competitive programming. Letâs discuss certain shorthand to deal with this problem in Python. Method #1: Using list comprehension
3 min read
Python - Remove index ranges from String
Given a string and ranges list, remove all the characters that occur in ranges. Input : test_str = 'geeksforgeeks is best for geeks', range_list = [(3, 6), (7, 10)] Output : geeks is best for geeks Explanation: The required ranges removed. Input : test_str = 'geeksforgeeks is best for geeks', range_
3 min read
Remove Special Characters from String in Python
When working with text data in Python, it's common to encounter strings containing unwanted special characters such as punctuation, symbols or other non-alphanumeric elements. For example, given the input "Data!@Science#Rocks123", the desired output is "DataScienceRocks123". Let's explore different
2 min read
Remove Duplicate Strings from a List in Python
Removing duplicates helps in reducing redundancy and improving data consistency. In this article, we will explore various ways to do this. set() method converts the list into a set, which automatically removes duplicates because sets do not allow duplicate values. [GFGTABS] Python a = ["Learn
3 min read
Python - Remove after substring in String
Removing everything after a specific substring in a string involves locating the substring and then extracting only the part of the string that precedes it. For example we are given a string s="Hello, this is a sample string" we need to remove the part of string after a particular substring includin
3 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