I'm trying to replace only one instance of a specific word in a string using regex, where the word that needs to be substituted appears at least twice. For instance I have the following:
The NOUN is ADJECTIVE and is completely different from the NOUN.
so far I have:
content = 'The NOUN is ADJECTIVE and is completely different from the NOUN.'
noun = input('Enter a noun: ')
adj = input('Enter an adjective: ')
noun_1 = input('Enter another noun: ')
names_regex_noun = re.compile(r'NOUN')
content = names_regex_noun.sub(noun, content)
names_regex_adj = re.compile(r'ADJECTIVE')
content = names_regex_adj.sub(adj, content)
names_regex_noun_1 = re.compile(r'NOUN')
content = names_regex_noun_1.sub(noun_1, content)
print(content)
The problem that I'm having is that when using names_regex_noun.sub(noun, content) it is replacing both instances of NOUN in content. I would like to only replace the first and leave the second instance of NOUN unaffected so that it could be substituted by noun_1.
x="abc abc abc"
print re.sub(r"abc\s*","",x,count=1)
Output:abc abc
re.sub(pattern, repl, string, count=0, flags=0)`
use `count=1`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With