php's strtr for python

后端 未结 5 948
遇见更好的自我
遇见更好的自我 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:07

    The answers on this thread are so out-dated. Here we go...

    Option #1: Use the str.format() function to handle this:

    "Hello there {first_name} {last_name}".format(first_name="Bob", last_name="Roy")
    

    Option #2: Use the Template class

    from string import Template
    t = Template('Hello there $first_name $last_name')
    t.substitute(first_name="Bob", last_name="Roy")
    

    Reference: Python String Formatting Best Practices

提交回复
热议问题