Search code examples
pythonstringcastingdigitinverse

Inverse one digit in string with python


I want to inverse a digit in a 3 digit string with Python. When I have string like below:

000

I want to inverse only one from 3 digits at once. So I want to have:

100 or 010 or 001

I am able to do this with something like:

tmp = 000
first = int(not(int(tmp[0]))),tmp[1],tmp[2]

And I'm getting:

(1, '0', '0') #instead of 100

So I guess, I need other casting etc..

Can I do the same in much more efficient and simpler way? This kind of casting is annoying. Thanks for every idea!


Solution

  • Using a dictionary with the inverse value would work:

    >>> flip = {'0': '1', '1':'0'}
    >>> s = '000'
    >>> flip[s[0]] + s[1:]
    '100'
    >>> s[0] + flip[s[1]] + s[2]
    '010'
    >>> s[:2] + flip[s[-1]]
    '001'