Reputation: 385
I have a sentence like this:
sentence = "it is a stupid book and a stupid hat and a stupid computer"
and I want to replace the word "stupid" with the word "silly". And create a sentence for each replacement.
The result is something like this:
"it is a silly book and a stupid hat and a stupid computer"
"it is a stupid book and a silly hat and a stupid computer"
"it is a stupid book and a stupid hat and a silly computer"
I mean the creating just 3 sentences each one for each replacement.
I found the method replace()
in Python but the count parameter determines the number of replacements not the one that I want. Could anyone help me?
Upvotes: 1
Views: 124
Reputation: 689
A robust but not elegant way is to first split the sentence by the word you want to replace. And then concatenate the pieces with different combinations of linking words:
sentence = "it is a stupid book and a stupid hat and a stupid computer"
old = "stupid"
new = "silly"
pieces = sentence.split(old)
new_sentences = []
for pos in range(1, len(pieces)):
new_sentences.append(old.join(pieces[:pos]) + new + old.join(pieces[pos:]))
print(new_sentences)
Thanks for @user3840170 making it shorter and easier to remember.
Output:
['it is a silly book and a stupid hat and a stupid computer',
'it is a stupid book and a silly hat and a stupid computer',
'it is a stupid book and a stupid hat and a silly computer']
Upvotes: 3
Reputation: 27588
Regex solution:
import re
sentence = "it is a stupid book and a stupid hat and a stupid computer"
for match in re.finditer(r'\bstupid\b', sentence):
print(sentence[:match.start()] + 'silly' + sentence[match.end():])
Upvotes: 3
Reputation: 321
One solution:
string = "it is a stupid book and a stupid hat and a stupid computer"
for i in range(string.count('stupid')):
new = string.replace('stupid', 'silly', i+1)
new = new.replace('silly', 'stupid', i)
print(new)
EDIT
Another solution with a list comprehension:
string = "it is a stupid book and a stupid hat and a stupid computer"
word1 = 'stupid'
word2 = 'silly'
strings = [string.replace(word1, word2, i+1).replace(word2, word1, i) for i in range(string.count(word1))]
print(strings)
EDIT2
If word2
happens to be in string
(as W. Ding comment), then you can try this (choosing an unlikely
string as long as you want):
string = "silly...it is a stupid book and a stupid hat and a stupid computer"
word1 = 'stupid'
word2 = 'silly'
unlikely = '$*$ù^$*ù*;;;,:;!::*ù*$^^$$^d^^d^eêê'
strings = [string.replace(word1, unlikely, i+1).
replace(unlikely, word1, i).
replace(unlikely, word2) for i in range(string.count(word1))]
print(strings)
Upvotes: 3