Python: How can i invert string "0110010"?
Question:
How to convert strings containing only 0s and 1s in most efficient and elegant way?
Ex:
input: "0110010"
output: "1001101"
Thanks in advance.
Answers:
This piece of code works with strings, try it:
>>> from string import maketrans
>>>
>>> initial_string = "10101010100011010"
>>> converted_string = initial_string.translate(maketrans("10","01"))
>>> converted_string # The result is
'01010101011100101'
>>>
How to do this with either strings or binary literals.
Easy, use a bitwise operator. This is the proper way to do it, because it’s useful to understand how to use these operators in Python. If this is a task, this seems like the way whoever set the task wanted it to be done.
# Make binary literal (0b prefix)
b = 0b11001001
# And use the complement operator
print(~b)
#Or if you want to print out the binary, try
print(bin(~b))
Here are some examples:
>>> ~0b110011
-52
>>> bin(~0b110001)
'-0b110010'
>>> bin(~0b11000)
'-0b11001'
If your binary number is a string:
s = "101"
# bin(~int(s,2)) = "010"
Note, you might want to trim the first three characters off of the space if you want just the binary characters, e.g.
bin(~int(s,2))[3:]
The simple way by use swapping:
st = "0110010"
st=st.replace("0","a")
st=st.replace("1","0")
st=st.replace("a","1")
print (st)
''.join('1' if x == '0' else '0' for x in '0110010')
How to convert strings containing only 0s and 1s in most efficient and elegant way?
Ex:
input: "0110010"
output: "1001101"
Thanks in advance.
This piece of code works with strings, try it:
>>> from string import maketrans
>>>
>>> initial_string = "10101010100011010"
>>> converted_string = initial_string.translate(maketrans("10","01"))
>>> converted_string # The result is
'01010101011100101'
>>>
How to do this with either strings or binary literals.
Easy, use a bitwise operator. This is the proper way to do it, because it’s useful to understand how to use these operators in Python. If this is a task, this seems like the way whoever set the task wanted it to be done.
# Make binary literal (0b prefix)
b = 0b11001001
# And use the complement operator
print(~b)
#Or if you want to print out the binary, try
print(bin(~b))
Here are some examples:
>>> ~0b110011
-52
>>> bin(~0b110001)
'-0b110010'
>>> bin(~0b11000)
'-0b11001'
If your binary number is a string:
s = "101"
# bin(~int(s,2)) = "010"
Note, you might want to trim the first three characters off of the space if you want just the binary characters, e.g.
bin(~int(s,2))[3:]
The simple way by use swapping:
st = "0110010"
st=st.replace("0","a")
st=st.replace("1","0")
st=st.replace("a","1")
print (st)
''.join('1' if x == '0' else '0' for x in '0110010')