zoukankan      html  css  js  c++  java
  • Python3字符串替换replace(),translate(),re.sub()

    Python3的字符串替换,这里总结了三个函数,replace()translate()re.sub()

    replace()

    python 中的 replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次

    str.replace(old, new[, max])

    a = 'Hello,world. ByeBye!'
    print(a.replace('l','Q'))
    print(a.replace('abcdefghi','0123456789'))
    print(a.replace('world','apple'))
    
    HeQQo,worQd. ByeBye!
    Hello,world. ByeBye!
    Hello,apple. ByeBye!
    

    可见,replace()函数可以替换string中的单个字符,也可以替换连续的字符,但无法生成字符替换映射表

    敲黑板!

    pandas 里面也有一个replace()函数,其用法更加多样化。比如,可以加入一个字典,用于替换对不同的值进行替换。

    s = pd.Series([0, 1, 2, 3, 4])
    s.replace({0:'a',1:'b'})
    Out[2]: 
    0    a
    1    b
    2    2
    3    3
    4    4
    dtype: object
    

    translate()

    translate()函数也是python自带。与replace() 函数不同的是,这里使用str.maketrans函数来创建一个表,它可以使用各种参数,但是需要三个Arguments。

    str.maketrans('','',del)

    第一个参数为被替换的字符,第二个参数为替换的字符,第三个参数为要删除的字符

    import string
    a = 'Hello,world. ByeBye!'
    remove = string.punctuation
    table = str.maketrans('abcdefgh','01234567',remove)
    print(a.translate(table))
    
    H4lloworl3 By4By4
    

    string.punctuation返回所有的标点符号,更多字符串常量如下图:

    str.maketrans()的前两个参数相当于一个映射表,如上述结果,所有的'e'被替换成了'4'

    第三个参数为要删除的字符,上述例子删除了所有的标点符号,如果要删除的字符还要加上空格的话,则可以这样:

    table = str.maketrans('abcdefgh','01234567',remove+' ')
    print(a.translate(table))
    
    H4lloworl3By4By4
    

    re.sub()

    这个是re库里的函数,其原型为re.sub(pattern, repl, string, count)

    第一个参数为正则表达式需要被替换的参数,第二个参数是替换后的字符串,第三个参数为输入的字符串,第四个参数指替换个数。默认为0,表示每个匹配项都替换。

    import re
    a = 'Hello,world. ByeBye!'
    print(re.sub(r'[A-Z]', '8', a))
    
    8ello,world. 8ye8ye!
    

    上述例子是把所有的大写字母替换成8,下述表示只替换前2个这样的大写字母。

    print(re.sub(r'[A-Z]', '8', a, 2))
    
    8ello,world. 8yeBye!
    
    • Reference:
    1. Python3 replace()方法
    2. NLP-python3 translate()报错问题-TypeError: translate() takes exactly one argument (2 given
    3. Python 标准库笔记:string模块
    4. 关于python 的re.sub用法
  • 相关阅读:
    Struts2框架详解
    Eclipse利用Axis2插件构建Web Service并测试
    解决JS中各浏览器Date格式不兼容的问题
    Struts2框架下表单数据的流向以及映射关系
    JMS总结
    第一次博客园
    微信OAuth2网页授权
    将List转换成DataTable
    对文件的读写操作
    Excel文件的导出操作
  • 原文地址:https://www.cnblogs.com/bjwu/p/9038910.html
Copyright © 2011-2022 走看看