Python | Extract characters except of K string
Last Updated :
01 Jun, 2023
Sometimes, while working with Python strings, we can have a problem in which we require to extract all the elements of string except those which present in a substring. This is quite common problem and has application in many domains including those of day-day and competitive programming. Lets discuss certain ways in which this task can be performed.
Method #1: Using loop This is brute force approach to this problem. In this we employ not operator to test for element presence in master string and extract it if the element is not present in K string.
Python3
# Python3 code to demonstrate working of
# Extract characters except of K string
# Using loop
# initializing strings
test_str1 = "geeksforgeeks is best"
test_str2 = "fes"
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Extract characters except of K string
# Using loop
res = []
for ele in test_str1:
if ele not in test_str2:
res.append(ele)
res = ''.join(res)
# printing result
print("String after removal of substring elements : " + str(res))
Output : The original string 1 is : geeksforgeeks is best
The original string 2 is : fes
String after removal of substring elements : gkorgk i bt
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using set operations This task can also be performed by including set operations. One can perform a set difference to get the difference of elements. The drawbacks are that order is not preserved and duplicates are removed.
Python3
# Python3 code to demonstrate working of
# Extract characters except of K string
# Using set operations
# initializing strings
test_str1 = "geeksforgeeks is best"
test_str2 = "fes"
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Extract characters except of K string
# Using set operations
res = ''.join(list(set(test_str1) - set(test_str2)))
# printing result
print("String after removal of substring elements : " + str(res))
Output : The original string 1 is : geeksforgeeks is best
The original string 2 is : fes
String after removal of substring elements : oti krbg
Time Complexity: O(1)
Auxiliary Space: O(n)
Method#3: Using re.sub() : This task can also be performed using re.sub function. re.sub() function is used to substitute the matched pattern with the another string. We can use empty string for substituting which work as we erase all the matched character in string.
Python3
# # Python3 code to demonstrate working of
# Extract characters except of K string
# Using re.sub
import re
# initializing strings
test_str1 = "geeksforgeeks is best"
test_str2 = "fes"
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Extract characters except of K string
# Using re.sub
res = re.sub(f'[{test_str2}]', "", test_str1)
# printing result
print("String after removal of substring elements : " + str(res))
OutputThe original string 1 is : geeksforgeeks is best
The original string 2 is : fes
String after removal of substring elements : gkorgk i bt
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using replace() method
Python3
# Python3 code to demonstrate working of
# Extract characters except of K string
# Using loop and replace()
# initializing strings
test_str1 = "geeksforgeeks is best"
test_str2 = "fes"
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Extract characters except of K string
# Using loop and replace()
for i in test_str2:
test_str1=test_str1.replace(i,"")
# printing result
print("String after removal of substring elements : " + str(test_str1))
OutputThe original string 1 is : geeksforgeeks is best
The original string 2 is : fes
String after removal of substring elements : gkorgk i bt
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5 : Using split() and join() methods
Approach
- Initiate a for loop to traverse test_str2
- Split test_str1 by each character of test_str2 and join test_str1 by empty string every time
- Finally at the end display test_str1
Python3
# Python3 code to demonstrate working of
# Extract characters except of K string
# initializing strings
test_str1 = "geeksforgeeks is best"
test_str2 = "fes"
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Extract characters except of K string
# Using loop and replace()
for i in test_str2:
test_str1=test_str1.split(i)
test_str1="".join(test_str1)
# printing result
print("String after removal of substring elements : " + str(test_str1))
OutputThe original string 1 is : geeksforgeeks is best
The original string 2 is : fes
String after removal of substring elements : gkorgk i bt
Time Complexity : O(N*M) N - length of test_str2 M -length of test_str1
Auxiliary Space : O(1) since we are displaying test_str1 as output
Method 6 : Using a list comprehension with a conditional statement.
Initialize two strings test_str1 and test_str2.
Print the original strings using print() function.
Use a list comprehension with a conditional statement to extract all characters in the first string test_str1 that are not present in the second string test_str2.
Use the join() method to join the list of extracted characters into a single string.
Store the result in a variable called result_str.
Print the result using print() function.
Python3
# initializing strings
test_str1 = "geeksforgeeks is best"
test_str2 = "fes"
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Extract characters except of K string
# Using list comprehension with a conditional statement
result_str = ''.join([char for char in test_str1 if char not in test_str2])
# printing result
print("String after removal of substring elements : " + str(result_str))
OutputThe original string 1 is : geeksforgeeks is best
The original string 2 is : fes
String after removal of substring elements : gkorgk i bt
Time complexity: O(n), where n is the length of the first string.
Auxiliary space: O(k), where k is the length of the second string.
Method #7: Using str.translate() method
Python3
# Initializing strings
test_str1 = "geeksforgeeks is best"
test_str2 = "fes"
# Printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Creating translation table
translation_table = str.maketrans('', '', test_str2)
# Applying translation table to remove substring elements
result_str = test_str1.translate(translation_table)
# Printing result
print("String after removal of substring elements: " + str(result_str))
OutputThe original string 1 is : geeksforgeeks is best
The original string 2 is : fes
String after removal of substring elements: gkorgk i bt
Time Complexity: The time complexity for this method is O(n), where n is the length of the input string test_str1.
Auxiliary Space: The auxiliary space complexity is O(1) since the space used is constant, irrespective of the size of the input string.
Similar Reads
Get Last N characters of a string - Python We are given a string and our task is to extract the last N characters from it. For example, if we have a string s = "geeks" and n = 2, then the output will be "ks". Let's explore the most efficient methods to achieve this in Python.Using String Slicing String slicing is the fastest and most straigh
2 min read
Python - Extract range characters from String Given a String, extract characters only which lie between given letters. Input : test_str = 'geekforgeeks is best', strt, end = "g", "s" Output : gkorgksiss Explanation : All characters after g and before s are retained. Input : test_str = 'geekforgeeks is best', strt, end = "g", "r" Output : gkorgk
4 min read
Python - Extract only characters from given string To extract only characters (letters) from a given string we can use various easy and efficient methods in Python. Using str.isalpha() in a Loop str.isalpha() method checks if a character in a string is an alphabetic letter. Using a loop, we can iterate through each character in a string to filter ou
2 min read
Python - Extract String after Nth occurrence of K character Given a String, extract the string after Nth occurrence of a character. Input : test_str = 'geekforgeeks', K = "e", N = 2 Output : kforgeeks Explanation : After 2nd occur. of "e" string is extracted. Input : test_str = 'geekforgeeks', K = "e", N = 4 Output : ks Explanation : After 4th occur. of "e"
7 min read
Python - Lowercase Kth Character in string The problem of lowercasing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the Nth character of string to lowercase. Letâs discuss certain ways in which this can be performed. Method #1 : Using string slicing +
4 min read
Python - Extract Upper Case Characters Sometimes, while working with strings, we are concerned about the case sensitivity of strings and might require getting just a specific case of character in a long string. Letâs discuss certain ways in which only uppercase letters can be extracted from a string. Method #1: Using list comprehension +
6 min read
Python | K Character Split String The problems and at the same time applications of list splitting is quite common while working with python strings. Some characters are usually tend to ignore in the use cases. But sometimes, we might not need to omit those characters but include them in our programming output. Letâs discuss certain
4 min read
Python | Extract suffix after K Sometimes, we might have a use case in which we need to find a suffix in a string. But sometimes, the requirement can be something dynamic like a specific input character than a number of elements for the decision of getting suffix. Letâs discuss certain ways in which we can find suffixes of the str
5 min read
Split string on Kth Occurrence of Character - Python The task is to write Python program to split a given string into two parts at the KáµÊ° occurrence of a specified character. If the character occurs fewer than K times return the entire string as the first part and an empty string as the second part. For example, in the string "a,b,c,d,e,f", splitting
3 min read
Python - Remove characters till K element Sometimes, while working with Python, we can have problem in which we need to get all elements in list occurring after particular character in list. This kind of problem can have application in data domains and web development. Lets discuss certain ways in which this task can be performed. Method #1
5 min read