微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从字符串中删除字符

如何解决从字符串中删除字符

我正在尝试通过此代码从字符串中删除“not”并将“poor”替换为“good”

def replace(sth):
    if 'poor' in sth :
        sth=sth.replace('poor','good')
        return sth
    if 'not' in sth:
         sth=sth.replace('not','')
         return sth
print(replace("This is not poor"))

输出是:

This is not good

我不明白为什么“不”没有被删除,而“差”被成功地替换为“好”

解决方法

你可以使用 from sub() 正则表达式 're'

喜欢: 进口重新 ... re.sub('not','',sth,flags=re.IGNORECASE) // 不区分大小写 re.sub('poor','good',flags=re.IGNORECASE) ...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。