UsuallyHelpless
UsuallyHelpless

Reputation: 119

Replace every instance of a word with another word without breaking other words containing that word

Word, word, word... Sorry for the title.

Let's say I want to replace every instance of "yes" to "no" in a string. I can just use string.replace(). But then there's this problem:

string = "yes eyes yesterday yes"
new_str = string.replace("yes", "no")

# new_str -> "no eno noterday no"

How can I preserve "eyes" and "yesterday" as is, with changing "yes" to "no".

Upvotes: 1

Views: 1249

Answers (4)

MarianD
MarianD

Reputation: 14151

" ".join(["no" if word=="yes" else word for word in string.split()])
'no eyes yesterday no'

The explanation:

First, break the string into a list of individual words:

string.split()
['yes', 'eyes', 'yesterday', 'yes']

Then iterate over this list of individual words and use the expression

"no" if word=="yes" else word

to replace every "yes" with "no" in a list comprehension

["no" if word=="yes" else word for word in string.split()]
['no', 'eyes', 'yesterday', 'no']

Finally, return this changed list back to a string with the .join() method of the string " " (the delimiter).

Upvotes: 3

Shubham Sharma
Shubham Sharma

Reputation: 71689

Try this:

import re

string = "yes eyes yesterday yes"
new_str = re.sub(r"\byes\b", "no", string)

Output:

no eyes yesterday no

Upvotes: 3

user3980558
user3980558

Reputation:

If you use regex, you can specify word boundaries with \b:

import re

sentence = 'yes no yesyes'

sentence = re.sub(r'\byes\b', 'no', sentence)
print(sentence)

Output:

no no yesyes

Notice that 'yesyes' is not changed (to 'no').

You can read more about Python's re module here.

Upvotes: 1

Ch3steR
Ch3steR

Reputation: 20669

You can use re here.

re.sub(r'\byes\b','no',"yes eyes yesterday yes")
# 'no eyes yesterday no'

From docs:

\b- Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string. This means that r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'.

Upvotes: 5

Related Questions