Posts Tagged ‘replace’

replace characters in a string

December 16, 2016 Leave a comment

You have a string, and you want to replace some characters to some other characters. The first thing that pops into mind is “replace”:

>>> s = "ebbe"
>>> s.replace('e', 'a')

But what if you need to replace 1s to 0s and 0s to 1s in “100”? The result, in this case, should be “011”.

A straightforward solution would be to use a “temporary variable”, in this case a third kind of character:

>>> s = "100"
>>> s.replace('1', 't').replace('0', '1').replace('t', '0')

A more elegant way is to use “translate”:

>>> s = "100"
>>> s.translate(str.maketrans('01', '10'))

More info here: .

Categories: python Tags: , ,