美文网首页
Python replace 函数增加正则支持

Python replace 函数增加正则支持

作者: 茄子_0937 | 来源:发表于2020-08-12 17:44 被阅读0次

Python 的 replace 方法没有正则功能,所以对字符串的替换有局限。 re 模块的 re.sub 可以利用正则进行字符替换,但是使用比较麻烦,字符串多次替换显得笨拙。所以我,利用re.sub 的正则功能,对字符串的replace方法进行了改造。

import re
 
class string(str):
    def replace(self,regex,cls):
        self = re.sub(regex,cls,self)
        this = string(self)
        return this
 
a = '{ name : abc}'
b = string(a)
b.replace('{\s*','{"').replace('\s*:\s*','":"').replace('\s*}','"}')

相关文章

网友评论

      本文标题:Python replace 函数增加正则支持

      本文链接:https://www.haomeiwen.com/subject/bldidktx.html