简体   繁体   中英

How to add space before or after if there is no space for a particular word in python without regex

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

Without regex

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()

With regex

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM