I have a string like below.
txt1 = "Krish is a school boy and Mahesh is anotherschool boy, Gang is good schoolboy"
Currently I am replacing school word with spaces as below
txt1.lower().replace("school"," school ")
But, due to above replace, it is adding another space, although there is a space, which means I am getting output as below. Is there a way if there is no space then only add space.
'krish is a school boy and mahesh is another school boy, gang is good school boy'
I am expecting output like below: Any best way to handle this case, without regex.
'Krish is a school boy and Mahesh is another school boy, Gang is good school boy'
Note: please ignore case sensitivity
I would add a replacement for 2 spaces into one .replace(" ", " ")
and a strip()
in case you had the word as first of last word
txt1 = "Krish is a school boy and Mahesh is anotherschool boy, Gang is good schoolboy"
txt1 = txt1.lower().replace("school", " school ").replace(" ", " ").strip()
import re
txt1 = "Krish is a school boy and Mahesh is anotherschool boy, Gang is good schoolboy"
txt1 = re.sub(r"school(\S)", r"school \1", txt1)
txt1 = re.sub(r"(\S)school", r"\1 school", txt1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.