我有一个像下面这样的字符串。
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'
我期望输出如下:任何最好的方法来处理这种情况,没有regex。
'Krish is a school boy and Mahesh is another school boy, Gang is good school boy'
注意:请忽略大小写敏感性
不带regex
我会在一个.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)