php's strtr for python

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

    Here is a naive algorithm:

    Use an index to walk the original string character by character and check for each index whether one of the search strings is equal to the string from the current index on. If a match is found, push the replacement in a buffer and proceed the index by the length of the matched string. If no match is found, proceed the index by one. At the end, concatenate the strings in the buffer to a single string.

    def strtr(strng, replace):
        buffer = []
        i, n = 0, len(strng)
        while i < n:
            match = False
            for s, r in replace.items():
                if strng[i:len(s)+i] == s:
                    buffer.append(r)
                    i = i + len(s)
                    match = True
                    break
            if not match:
                buffer.append(strng[i])
                i = i + 1
        return ''.join(buffer)
    

提交回复
热议问题