Replace multiple characters in a string

后端 未结 4 661
感情败类
感情败类 2020-12-18 11:59

Is there a simple way in python to replace multiples characters by another?

For instance, I would like to change:

name1_22:3-3(+):Pos_bos 
         


        
4条回答
  •  不知归路
    2020-12-18 12:45

    Use a translation table. In Python 2, maketrans is defined in the string module.

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

    In Python 3, it is a str class method.

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

    In both, the table is passed as the argument to str.translate.

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

    In Python 3, you can also pass a single dict mapping input characters to output characters to maketrans:

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

提交回复
热议问题