How to replace or remove a word in a string in python ?

September 28, 2021    /    Viewed: 253    /    Comments: 0    /    Edit


Examples of how to replace or remove a word in a string in python:

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 ?

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!