php's strtr for python

后端 未结 5 965
遇见更好的自我
遇见更好的自我 2020-12-06 18:39

php has the strtr function:

strtr(\'aa-bb-cc\', array(\'aa\' => \'bbz\', \'bb\' => \'x\', \'cc\' => \'y\'));
# bbz-x-y

It replace

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 19:17

    The following uses regular expressions to do it:

    import re
    
    def strtr(s, repl):
      pattern = '|'.join(map(re.escape, sorted(repl, key=len, reverse=True)))
      return re.sub(pattern, lambda m: repl[m.group()], s)
    
    print(strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'}))
    

    Like the PHP's version, this gives preference to longer matches.

提交回复
热议问题