【问题标题】:Replace multiple characters in a string替换字符串中的多个字符
【发布时间】:2019-03-21 12:36:55
【问题描述】:

python 中有没有一种简单的方法可以用另一个字符替换多个字符?

例如,我想改变:

name1_22:3-3(+):Pos_bos 

name1_22_3-3_+__Pos_bos

所以基本上用"_"替换所有"(",")",":"

我只知道这样做:

str.replace(":","_")
str.replace(")","_")
str.replace("(","_")

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    您可以使用re.sub 将多个字符替换为一种模式:

    import re
    s = 'name1_22:3-3(+):Pos_bos '
    re.sub(r'[():]', '_', s)
    

    输出

    'name1_22_3-3_+__Pos_bos '
    

    【讨论】:

      【解决方案2】:

      使用翻译表。在 Python 2 中,maketrans 定义在 string 模块中。

      >>> import string
      >>> table = string.maketrans("():", "___")
      

      在 Python 3 中,它是一个str 类方法。

      >>> table = str.maketrans("():", "___")
      

      在这两种情况下,表都作为参数传递给str.translate

      >>> 'name1_22:3-3(+):Pos_bos'.translate(table)
      'name1_22_3-3_+__Pos_bos'
      

      在 Python 3 中,您还可以传递单个 dict 映射输入字符到输出字符到 maketrans

      table = str.maketrans({"(": "_", ")": "_", ":": "_"})
      

      【讨论】:

        【解决方案3】:

        坚持你目前使用replace()的方法:

        s =  "name1_22:3-3(+):Pos_bos"
        for e in ((":", "_"), ("(", "_"), (")", "__")):
            s = s.replace(*e)
        print(s)
        

        输出

        name1_22_3-3_+___Pos_bos
        

        编辑:(为了可读性)

        s =  "name1_22:3-3(+):Pos_bos"
        replaceList =  [(":", "_"), ("(", "_"), (")", "__")]
        
        for elem in replaceList:
            print(*elem)          # : _, ( _, ) __  (for each iteration)
            s = s.replace(*elem)
        print(s)
        

        repList = [':','(',')']   # list of all the chars to replace
        rChar = '_'               # the char to replace with
        for elem in repList:
            s = s.replace(elem, rChar)
        print(s)
        

        【讨论】:

          【解决方案4】:

          另一种可能性是使用所谓的列表推导结合所谓的三元条件运算符如下方式:

          text = 'name1_22:3-3(+):Pos_bos '
          out = ''.join(['_' if i in ':)(' else i for i in text])
          print(out) #name1_22_3-3_+__Pos_bos
          

          因为它给出了list,所以我使用''.join 将字符的list(长度为1 的strs)更改为str

          【讨论】:

            猜你喜欢
            • 2015-03-15
            • 1970-01-01
            • 1970-01-01
            • 2016-09-10
            • 1970-01-01
            • 2015-03-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多