Sometimes, while working with Python strings, we can have a problem in which we need to remove all the words from a string which are a part of key of dictionary. This problem can have application in domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using split() + loop + replace()
The combination of above functions can be used to solve this problem. In this, we perform the task of converting string to list of words using split(). Then we perform a replace of word present in string with empty string using replace().
# Python3 code to demonstrate working of # Remove Dictionary Key Words # Using split() + loop + replace() # initializing string test_str = 'gfg is best for geeks' # printing original string print ( "The original string is : " + str (test_str)) # initializing Dictionary test_dict = { 'geeks' : 1 , 'best' : 6 } # Remove Dictionary Key Words # Using split() + loop + replace() for key in test_dict: if key in test_str.split( ' ' ): test_str = test_str.replace(key, "") # printing result print ( "The string after replace : " + str (test_str)) |
The original string is : gfg is best for geeks The string after replace : gfg is for
Method #2 : Using join() + split()
This is yet another way in which this task can be performed. In this, we reconstruct new string using join(), performing join by the empty string after split.
# Python3 code to demonstrate working of # Remove Dictionary Key Words # Using join() + split() # initializing string test_str = 'gfg is best for geeks' # printing original string print ( "The original string is : " + str (test_str)) # initializing Dictionary test_dict = { 'geeks' : 1 , 'best' : 6 } # Remove Dictionary Key Words # Using join() + split() temp = test_str.split( ' ' ) temp1 = [word for word in temp if word.lower() not in test_dict] res = ' ' .join(temp1) # printing result print ( "The string after replace : " + str (res)) |
The original string is : gfg is best for geeks The string after replace : gfg is for
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.