-2

If I want to use translate on more than one unicode character like:

'banana'.translate({ord('ba'):u'cd'})

How can I do this? ord works on only one character. So what can make this happen?

Note: The solution explained in How to replace multiple substrings of a string? is not a Python3 compatible solution. I tried to modify the iteritems as per iteritems in Python but couldn't make it working. I am new to python I don't know how to make this work.

CS13
  • 1
  • 2
  • 3
    I don't think you can, sadly... translate is optimised for character replacements, not substring replacements. – cs95 Mar 19 '18 at 15:19
  • I understand. But if I want to have alternative implementation what can it be? How can I achieve such a result? – CS13 Mar 19 '18 at 15:21
  • 2
    Is it just this one replacement? Then `banana.replace('ba', 'cd')`. – cs95 Mar 19 '18 at 15:22
  • Thanks. But, I'm looking for multiple replacements. – CS13 Mar 19 '18 at 15:26
  • It's not clear wether you want to replace "ba" with "cd" or replace "b" with "c" and "a" with "d" or something else... – bruno desthuilliers Mar 19 '18 at 15:27
  • Possible duplicate of [How to replace multiple substrings of a string?](https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string) – pault Mar 19 '18 at 15:29
  • "ord works on only one character" - I understand this already and the above comments clarifies further. – CS13 Mar 19 '18 at 15:30
  • The solution in [link](https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string) is not for python 3! – CS13 Mar 19 '18 at 17:28

1 Answers1

0

You may want to build your own function, mocking the translate behaviour:

def trans_mock(string, **kwargs):
    for k,v in kwargs.items():
        string= string.replace(k,v)
    return string

Where kwargs will be the strings you want to replace:

print trans_mock("banana", ba="cd", na="we") # output: cdwewe

you may even want to sortof override the string class and add trans_mock as method:

class string(str):
    def trans_mock(self, **kwargs):
        for k,v in kwargs.items():
            print k,v
            self = self.replace(k,v)
        return self

banana = string("banana")
print banana.trans_mock(ba="ct", na="lw") # output: ctlwlw
Gsk
  • 2,929
  • 5
  • 22
  • 29