Python - Flipping Binary 1's and 0's in a String

前端 未结 9 1860
日久生厌
日久生厌 2020-12-03 15:52

I\'m trying to take a binary number in string form and flip the 1\'s and 0\'s, that is, change all of the 1\'s in the string to 0\'s, and all of the 0\'s to 1\'s. I\'m new t

9条回答
  •  醉梦人生
    2020-12-03 16:11

    If speed is important:

    And you already have the decimal integer representing the binary string, then bit manipulation is slightly faster.

    bin((i ^ (2 ** (i.bit_length()+1) - 1)))[3:]
    

    If you are only given the binary string, then use the str.replace method given by @Amy:

    s.replace('1', '2').replace('0', '1').replace('2', '0')
    

    I tested the various methods proposed here, and the bit manipulation method, with this gist:

    Test Results

    i = 129831201;
    s = '111101111010001000100100001';
    

    Bit manipulation given decimal int:

    bin((i ^ (2 ** (i.bit_length()+1) - 1)))[3:]
    
    1000000 loops, best of 3: 0.647 usec per loop
    

    Bit manipulation given binary string:

    bin((int(s, 2) ^ (2**(len(s)+1) - 1)))[3:]
    
    1000000 loops, best of 3: 0.922 usec per loop
    

    Sequential str.replace:

    s.replace('1', '2').replace('0', '1').replace('2', '0')
    
    1000000 loops, best of 3: 0.619 usec per loop
    

    str.maketrans:

    s.translate(str.maketrans('10', '01'))
    
    1000000 loops, best of 3: 1.16 usec per loop
    

    ''.join with dictionary mapping:

    flip = {'1':'0', '0':'1'}; ''.join(flip[b] for b in s)
    
    100000 loops, best of 3: 2.78 usec per loop
    

    ''.join with conditional:

    ''.join('1' if b == '0' else '0' for b in s)
    
    100000 loops, best of 3: 2.82 usec per loop
    

提交回复
热议问题