繁体   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