In this article, we mentioned how to remove word from string in python, but if you want to know how to remove char from a string or sentence then you can read.
To begin with, removing the word from the string we have to be familiar with the list, string, and some of its built-in methods.
Before getting directly to the code we must understand the actual working of our problem and break it into smaller chunks and then conquer it.
- We will take a string.
- We will take desired input from the user which we want to discard from a string.
- We will convert our string into a list so that we can easily traverse it.
- We will take another variable called new_string, where we will store our output.
- We will iterate through the list.
- We will check if the word from iteration and input value from the user matches or not.
- If it matches, we will not inset into new_string.
- Else we will insert it into new_string.
- And finally, we will print the output.
- We have taken a string
- We have printed its value
- We have taken input from the user, which we want to discard.
- We have applied the split() method of string which splits the string and passes the output into a list. So, our string becomes a list.
- We have taken a new_string variable with an empty string. In this, we will store out output.
- We have iterated through the list, and each word of the list comes in i variables in each iteration.
- Now, we have checked if i and char content matches or not.
- If content is matched then we have applied join() method of string which joins whatever is inside join to the existing string, in this case it is empty space. Because if i and char matches we don’t want it to be joined to new_string.
- After inserting an empty space we have again inserted an empty string so the there is space between two words.
- We have taken an else block which means i and char are not equal.
- So, we have inserted the i value as it is in the new_string.
- Again, we have inserted an empty space so there can be spaces between two words.
- Simply printed the output.
This was how to remove words from the string. If you want to see how to remove char from string read this article.