美文网首页000python
re.sub()介绍和用法

re.sub()介绍和用法

作者: 天行_b6d0 | 来源:发表于2020-09-17 15:49 被阅读0次

    举个例子:

    str = "小明的数学:50,英语50"
    

    把这个字符串中的50改为100,我们一般可以使用replace实现

    r_str = str.replace("50","100")
    

    如果是这样的字符串:

    str = "小明数学考了20,英语考了30"
    

    想要把20和30都改成100,这样就没办法直接使用replace方法进行修改。
    而使用re.sub,用正则表达式就可以满足要求,当然其他各种更为复杂的替换也可以用re.sub来实现。

    re.sub是个正则表达式替换函数,对于输入的一个字符串,利用正则表达式(的强大的字符串处理功能),去实现(相对复杂的)字符串替换处理,然后返回被替换后的字符串,实现比普通字符串的replace更加强大的替换功能。

    re.sub的五个参数

    必选参数:pattern,repl,string

    pattern:表示正则中的模式字符串
    在pattern中使用(\N),也就是反斜杠加数字,对应匹配的组。
    比如说:

    import re
    Str = "ming is handsome,ming is really handsome"
    Rstr = re.sub(r"(\w+) is handsome,\1 is really handsome", "yan", Str)
    print ("replacedStr =", Rstr)  # Rstr = yan
    

    \1的意思是可以替换本句中已经使用小括号分好组的部分,本句中(\w+)为分好的小组,表示的内容是ming,后面\1即取前面(\w+)分组的内容,即取了ming。也就是说(\w+) is handsome,\1 is really handsome就是ming is handsome,ming is really handsome。

    repl:被替换字符
    string:被替换的字符串

    相关文章

      网友评论

        本文标题:re.sub()介绍和用法

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