字符串清洗

  • 字符串strip(), lstrip(), rstrip()方法去掉字符串两端字符

     a = "bbbbaacbaaaccc"
     b = a.strip("bc")
     aacbaaa
    
  • 字符串的replace()替换任意位置字符

     a = "bbbb\taaaaa\tccc"
     b = a.replace('\t', '')
     bbbbaaaaaccc
    
  • 正则表达式re.sub()删除任意位置字符

     import re
     a = "bbbb\taa\n\taaa\tc\rcc"
     b = re.sub('[\t\r\n]', '', a)
     bbbbaaaaaccc
    
  • 字符串stanslate()方法,可以同时删除多种不同字符
    bytearray.maketrans()、bytes.maketrans()、str.maketrans(), translate()
    str.maketrans(a, b) 参数1文中字符, 参数2替换成字符

     s = 'abc2222xyz'
     a = str.maketrans('2', '4')
     print(s.translate(a))
     abc4444xyz
    

bytes.maketrans() 并转下码

    s = b'123dddddxyz'
    a = bytes.maketrans(b'123', b'ABC')
    n = s.translate(a)
    print(n.decode()
    ABCdddddxyz
  • 删除字符串translate(), bytes类型

     s = '123dddddxyz'
     b = s.encode()
     c = b.translate(None, b'123xyz')
     print(c.decode())
     ddddd
    
  • 替换字符串的同时删除字符串

     s = b'123\txyrz\r'
     b = bytes.maketrans(b'123', b'ABC')
     ns = s.translate(b, b'\t\r')
     print(ns.decode())
     ABCxyrz
    

你可能感兴趣的:(Python)