zoukankan      html  css  js  c++  java
  • python中的maketrans和translate

    参考:http://wangwei007.blog.51cto.com/68019/1242206


    maketrans和translate在某一方面和string.replace很相似

    maketrans和translate使用:

    #string.maketrans(from, to): return  a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to;from and to must have the same length.
    #string.translate(s, table[, deletechars]): Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.
    
    import string
    
    str1 = '123[abc]123'
    table = string.maketrans('[]', '""') #from 和 to一一对应
    tmp_str = string.translate(str1, table)
    print tmp_str  #123"abc"123


    maketrans和translate结合可以一次替换多个字符,string.replace只能每次替换一个字符

    tmp_str1 = string.replace(str1, '[' , '"')
    tmp_str1 = string.replace(tmp_str1, ']' , '"')
    print tmp_str1  #123"abc"123


    另外,string.replace可以控制替换几次

    tmp_str2 = string.replace(str1, '1', 'A', 1) #第四个参数,表示替换几次
    print tmp_str2 #A23[abc]123



  • 相关阅读:
    day17---无参装饰器
    day17---作业
    python面向过程的编程思想
    算法之二分法
    python递归函数
    pyth作业3/25
    三元表达式、生成式、生成器表达式
    python 3/24作业
    python生成器
    python 迭代器
  • 原文地址:https://www.cnblogs.com/zhangjianzhi/p/3820862.html
Copyright © 2011-2022 走看看