Home > Enterprise >  How to add a string to a paragraph after a particular word Python
How to add a string to a paragraph after a particular word Python

Time:11-02

I am trying to insert a string after a specific word in a paragraph.

For example: If the word I am looking at is King in the paragraph, I want to add Arthur right after it so it will be like:

King Arthur went on a mission

for all the lines that has King instead of

King went on a mission

CodePudding user response:

This example uses re.sub to substitute King (not followed by Arthur) with King Arthur):

import re

s = "King went on a mission"

s = re.sub(r"\bKing\b(?!\s*Arthur)", "King Arthur", s)
print(s)

Prints:

King Arthur went on a mission
  • Related