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
# Python3 code to demonstrate working of
# Remove similar index elements in Strings
# Using join() + zip() + loop
# initializing strings
test_str1 = 'geeks'
test_str2 = 'beaks'
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# conversion to list for zipping
list1 = list(test_str1)
list2 = list(test_str2)
res1 = []
res2 = []
for ch1, ch2 in zip(list1, list2):
# check inequalities
if ch1 != ch2:
res1.append(ch1)
res2.append(ch2)
# conversion to string
res1 = "".join(res1)
res2 = "".join(res2)
# printing result
print("Modified String 1 : " + str(res1))
print("Modified String 2 : " + str(res2))
OutputThe 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
# Python3 code to demonstrate working of
# Remove similar index elements in Strings
# Using list comprehension
# initializing strings
test_str1 = 'geeks'
test_str2 = 'beaks'
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# one-liner to solve problem
res = ["".join(mastr) for mastr
in zip(*[(a, b) for a, b in zip(test_str1, test_str2) if a != b])]
# printing result
print("Modified String 1 : " + str(res[0]))
print("Modified String 2 : " + str(res[1]))
OutputThe 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
# Python3 code to demonstrate working of
# Remove similar index elements in Strings
# initializing strings
test_str1 = 'geeks'
test_str2 = 'beaks'
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# conversion to list for zipping
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)
# printing result
print("Modified String 1 : " + str(test_str1))
print("Modified String 2 : " + str(test_str2))
OutputThe 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
# initializing strings
test_str1 = 'geeks'
test_str2 = 'beaks'
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
res1 = ''.join([c for i, c in enumerate(test_str1) if c != test_str2[i]])
res2 = ''.join([c for i, c in enumerate(test_str2) if c != test_str1[i]])
# printing result
print("Modified String 1 : " + str(res1))
print("Modified String 2 : " + str(res2))
OutputThe 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
# Python code to demonstrate working of
# Remove similar index elements in Strings
# Using map() + lambda function + zip() + join()
# initializing strings
test_str1 = 'geeks'
test_str2 = 'beaks'
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# conversion to list and mapping and joining
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)))
# printing result
print("Modified String 1 : " + str(res1))
print("Modified String 2 : " + str(res2))
OutputThe 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
# initializing strings
test_str1 = 'geeks'
test_str2 = 'beaks'
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# creating a filter object to remove similar index elements
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))
# converting the filter object to a string
res1 = ''.join([x[0] for x in filter_obj1])
res2 = ''.join([x[0] for x in filter_obj2])
# printing the modified strings
print("Modified String 1 : " + str(res1))
print("Modified String 2 : " + str(res2))
OutputThe 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
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 | Split strings in list with same prefix in all elements
Sometimes we face a problem in which we have a list of strings and there are some garbage/unwanted letters at its prefix or suffix or at the specified position uniformly, i.e this extends to all the strings in the list. Let's discuss certain ways in which this problem can be solved. Method #1 : Usin
5 min read
Python - Elements with same index
Given a List, get all elements that are at their index value. Input : test_list = [3, 1, 8, 5, 4, 10, 6, 9]Â Output : [1, 4, 6]Â Explanation : These elements are at same position as its number.Input : test_list = [3, 10, 8, 5, 14, 10, 16, 9]Â Output : []Â Explanation : No number at its index. Method
5 min read
Python - Remove elements at Indices in List
Given List, remove all the elements present in the indices list in Python. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5]Â Output : [5, 6, 7, 2, 10]Â Explanation : 3, 6, and 1 has been removed. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2]Â Output : [5, 6, 7, 8,
7 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 | Rear elements from Tuple Strings
Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
5 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