Archive

Posts Tagged ‘replace’

replace characters in a string

December 16, 2016 Leave a comment

Problem
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')
'abba'

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

Solution
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')
'011'

A more elegant way is to use “translate”:

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

More info here: https://docs.python.org/3/library/stdtypes.html#str.maketrans .

Categories: python Tags: , ,