Opal24
Opal24

Reputation: 17

Python - Remove word only from within a sentence

I am trying to remove a specific word from within a sentence, which is 'you'. The code is as listed below:

out1.text_condition = out1.text_condition.replace('you','')

This works, however, it also removes it from within a word that contains it, so when 'your' appears, it removes the 'you' from within it, leaving 'r' standing. Can anyone help me figure out what I can do to just remove the word, not the letters from within another string?

Thanks!

Upvotes: 2

Views: 1467

Answers (3)

Rivers
Rivers

Reputation: 1923

In order to replace whole words and not substrings, you should use a regular expression (regex).

Here is how to replace a whole word with the module re:

import re

def replace_whole_word_from_string(word, string, replacement=""):
    regular_expression = rf"\b{word}\b"
    return re.sub(regular_expression, replacement, string)

string = "you you ,you your"

result = replace_whole_word_from_string("you", string)

print(result)

Output:

  , your

Explanation:

The two \b are what we call "word boundaries". The advantage over str.replace is that it will take into account the punctuation too.

In order to create the regular expression, here we use Literal String Interpolation (also called "f-strings", https://www.python.org/dev/peps/pep-0498/).

To create a "f-string", we add the prefix f.

We also use the prefix r, in order to create a "raw string". We use a raw string in order to avoid escaping the backslash in \b.

Without the prefix r, we would have written regular_expression = f"\\b{word}\\b".

If you had used string.replace(' you ', ' '), you would have received this (wrong) output:

you ,you your

Upvotes: 2

Yevhen Kuzmovych
Yevhen Kuzmovych

Reputation: 12140

A very simple solution is to replace the word with spaces around it with one space:

out1.text_condition = out1.text_condition.replace(' you ', ' ')

But note that it wouldn't remove for example you. (in the end of the sentence) or you,, etc.

Upvotes: 1

Eric
Eric

Reputation: 321

Easiest way is probably just to assume there are spaces before and after the word:

out1.text_condition = out1.text_condition.replace(' you ','')

Upvotes: 0

Related Questions