簡體   English   中英

如果沒有正則表達式的python中特定單詞沒有空格,如何在前后添加空格

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

我有一個像下面這樣的字符串。

txt1 = "Krish is a school boy and Mahesh is anotherschool boy, Gang is good schoolboy"

目前我正在用空格替換學校單詞,如下所示

txt1.lower().replace("school"," school ")

但是,由於上面的替換,它正在添加另一個空格,盡管有一個空格,這意味着我得到如下輸出。 如果沒有空間,有沒有辦法只添加空間。

'krish is a  school  boy and mahesh is another school  boy, gang is good  school boy'

我期待如下輸出:處理這種情況的最佳方法,沒有正則表達式。

'Krish is a school boy and Mahesh is another school boy, Gang is good school boy'

注意:請忽略區分大小寫

沒有正則表達式

我會將 2 個空格的替換添加到一個.replace(" ", " ")和一個strip()中,以防您將單詞作為最后一個單詞的第一個

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM