Python - Extract indices of Present, Non Index matching Strings
Last Updated :
10 May, 2023
Given two strings, extract indices of all characters from string 1 which are present in the other string, but not in the same index.
Input : test_str1 = 'pplg', test_str2 = 'pineapple'
Output : [0, 1, 2]
Explanation : ppl is found in 2nd string, also not on same index as 1st.
Input : test_str1 = 'pine', test_str2 = 'pineapple'
Output : []
Explanation : Found in other string on same index.
Method #1 : Using enumerate() + loop
In this, we employ a nested loop to check for each character its occurrence in 2nd string, and then if it's in other position, if found the index is appended.
Python3
# Python3 code to demonstrate working of
# Extract indices of Present, Non Index matching Strings
# using loop + enumerate()
# initializing strings
test_str1 = 'apple'
test_str2 = 'pineapple'
# printing original Strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# the replaced result
res = []
for idx, val in enumerate(test_str1):
# if present in string 2
if val in test_str2:
# if not present at same index
if test_str2[idx] != val:
res.append(idx)
# printing result
print("The extracted indices : " + str(res))
OutputThe original string 1 is : apple
The original string 2 is : pineapple
The extracted indices : [0, 1, 2, 3, 4]
Method #2 : Using enumerate() + zip() + list comprehension
In this, we perform the task of getting indices using enumerate() and pairing of both strings is done using zip(), the conditional checks occur using list comprehension.
Python3
# Python3 code to demonstrate working of
# Extract indices of Present, Non Index matching Strings
# using enumerate() + zip() + list comprehension
# initializing strings
test_str1 = 'apple'
test_str2 = 'pineapple'
# 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 this problem.
res = [idx for idx, (x, y) in enumerate(
zip(test_str1, test_str2)) if x != y and x in test_str2]
# printing result
print("The extracted indices : " + str(res))
OutputThe original string 1 is : apple
The original string 2 is : pineapple
The extracted indices : [0, 1, 2, 3, 4]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Use a for loop
- Initialize two empty lists, one for storing indices of present strings and another for storing indices of non-index matching strings.
- Iterate over each character and its index simultaneously using the built-in enumerate function.
- If the character from the first string is in the second string, append its index to the present strings list.
- If the characters at the same index from both strings are different, append the index to the non-index matching strings list.
- Print the final results.
Python3
# Python3 code to demonstrate an alternative approach for
# Extracting indices of Present, Non Index matching Strings
# initializing strings
test_str1 = 'apple'
test_str2 = 'pineapple'
# printing original Strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# initialize two empty lists
present_strs = []
non_index_matching_strs = []
# iterate over each character and its index using enumerate
for idx, char in enumerate(test_str1):
# check if character is present in the second string
if char in test_str2:
present_strs.append(idx)
# check if characters at the same index are different
if char != test_str2[idx]:
non_index_matching_strs.append(idx)
# printing results
print("Indices of Present strings : ", present_strs)
print("Indices of Non Index matching strings : ", non_index_matching_strs)
OutputThe original string 1 is : apple
The original string 2 is : pineapple
Indices of Present strings : [0, 1, 2, 3, 4]
Indices of Non Index matching strings : [0, 1, 2, 3, 4]
Time complexity: O(n), where n is the length of the first string.
Auxiliary space: O(k), where k is the number of indices that satisfy the conditions.
Method #4: Using a set intersection
- Create two strings test_str1 and test_str2.
- Print the original strings test_str1 and test_str2.
- Find the common characters between the two strings using set intersection and store them in the common_chars set.
- Create a list present_strs which stores the indices of characters in test_str1 that are present in common_chars.
- Create a list of non_index_matching_strs which stores the indices of characters in test_str1 that are not present in test_str2 or are not in the same position in both strings.
- Print the result by displaying the present_strs and non_index_matching_strs
Python3
test_str1 = 'apple'
test_str2 = 'pineapple'
# printing original Strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# using set intersection and list comprehension
common_chars = set(test_str1) & set(test_str2)
present_strs = [idx for idx, char in enumerate(test_str1) if char in common_chars]
non_index_matching_strs = [idx for idx, char in enumerate(test_str1) if char not in test_str2 or char != test_str2[idx]]
# printing results
print("Indices of Present strings : ", present_strs)
print("Indices of Non Index matching strings : ", non_index_matching_strs)
OutputThe original string 1 is : apple
The original string 2 is : pineapple
Indices of Present strings : [0, 1, 2, 3, 4]
Indices of Non Index matching strings : [0, 1, 2, 3, 4]
Time complexity: O(n), where n is the length of the first string test_str1.
Auxiliary space: O(n), as the present_strs and non_index_matching_strs lists can potentially store up to n elements each.
Method #5: set comprehension and zip() functions
Python3
# Python3 code to demonstrate another alternative approach for
# Extracting indices of Present, Non Index matching Strings
# initializing strings
test_str1 = 'apple'
test_str2 = 'pineapple'
# printing original Strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# using set comprehension to get the indices of present characters
present_strs = {idx for idx, char in enumerate(test_str1) if char in test_str2}
# using set comprehension to get the indices of non-index matching characters
non_index_matching_strs = {idx for idx, (char1, char2) in enumerate(zip(test_str1, test_str2)) if char1 != char2}
# printing results
print("Indices of Present strings : ", present_strs)
print("Indices of Non Index matching strings : ", non_index_matching_strs)
OutputThe original string 1 is : apple
The original string 2 is : pineapple
Indices of Present strings : {0, 1, 2, 3, 4}
Indices of Non Index matching strings : {0, 1, 2, 3, 4}
Time complexity: O(n), where n is the length of the input strings.
Auxiliary space: O(n)
Similar Reads
Python - Extract Indices of substring matches
Given a String List, and a substring, extract list of indices of Strings, in which that substring occurs. Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" Output : [0, 2, 3] Explanation : "Gfg" is present in 0th, 2nd and 3rd element as substring. Input : tes
5 min read
Python program to Extract Mesh matching Strings
Given a character mesh, containing missing characters, match the string which matches the mesh. Example: Input : test_list = ["geeks", "best", "peeks"], mesh = "_ee_s" Output : ['geeks', 'peeks'] Explanation : Elements according to mesh are geeks and peeks. Input : test_list = ["geeks", "best", "tes
4 min read
Character Indices Mapping in String List - Python
We are given a string list we need to map characters to their indices. For example, a = ["hello", "world"] so that output should be [[('h', 0), ('e', 1), ('l', 2), ('l', 3), ('o', 4)], [('w', 0), ('o', 1), ('r', 2), ('l', 3), ('d', 4)]].Using a nested for loopA nested for loop iterates through each
3 min read
Python - Find the sum of Length of Strings at given indices
Given the String list, write a Python program to compute sum of lengths of custom indices of list. Examples: Input : test_list = ["gfg", "is", "best", "for", "geeks"], idx_list = [0, 1, 4] Output : 10 Explanation : 3 + 2 + 5 = 10. (Sizes of strings at idx.) Input : test_list = ["gfg", "is", "best",
4 min read
Extract List of Substrings in List of Strings in Python
Working with strings is a fundamental aspect of programming, and Python provides a plethora of methods to manipulate and extract substrings efficiently. When dealing with a list of strings, extracting specific substrings can be a common requirement. In this article, we will explore five simple and c
3 min read
Find position of a character in given string - Python
Given a string and a character, our task is to find the first position of the occurrence of the character in the string using Python. For example, consider a string s = "Geeks" and character k = 'e', in the string s, the first occurrence of the character 'e' is at index1. Let's look at various metho
2 min read
Extract Substrings From A List Into A List In Python
Python is renowned for its simplicity and versatility, making it a popular choice for various programming tasks. When working with lists, one common requirement is to extract substrings from the elements of the list and organize them into a new list. In this article, we will see how we can extract s
2 min read
Python - Extract K length substrings
The task is to extract all possible substrings of a specific length, k. This problem involves identifying and retrieving those substrings in an efficient way. Let's explore various methods to extract substrings of length k from a given string in PythonUsing List Comprehension List comprehension is t
2 min read
Python | Extract Numbers in Brackets in String
Sometimes, while working with Python strings, we can have a problem in which we have to perform the task of extracting numbers in strings that are enclosed in brackets. Let's discuss the certain ways in which this task can be performed. Method 1: Using regex The way to solve this task is to construc
6 min read
Python program to find Indices of Overlapping Substrings
To count the number of overlapping sub-strings in Python we can use the Re module. To get the indices we will use the re.finditer() method. But it returns the count of non-overlapping indices only. Examples: Input: String: "geeksforgeeksforgeeks" ; Pattern: "geeksforgeeks" Output: [0, 8] Explanation
4 min read