Examples of how to replace or remove a word in a string in python:
Table of contents
Create a string in python
Let's first create a string in python
sentence = "Hello How are you today ?"
Replace or remove a word in a string
To replace or remove a word in a string, a solution is to use replace()
sentence = sentence.replace('Hello', "Hi")
print(sentence)
gives
Hi How are you today ?
Note that
sentence = sentence.replace('How are you today', "What's up")
print(sentence)
gives
Hi What's up ?
To remove a work, a solution is to replace it by nothing:
sentence = "Hello How are you today ?"
sentence = sentence.replace('Hello', "")
print(sentence)
gives
How are you today ?
Note: to remove leading whitespaces:
sentence = sentence.strip()
print(sentence)
gives
How are you today ?