本文介绍了Python中位串的逻辑或的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做的是得到两个位字符串的逻辑或结果.例如:
What i want to do is have the result of logical OR for two bit-strings. For example:
a='010010'
b='000101'
c=LOGIC_OR(a,b)
c
010111
我大多数时候遇到的错误是当我将'b'从字符串转换为二进制时,它会删除前导零.我使用过的其他方法将'a'和'b'转换为整数.通常,没有任何效果,将不胜感激.预先感谢
The error i encounter most of the time is when I convert 'b' from string to binary it removes leading zeros. Others methods i have used convert 'a' and 'b' to integers. Generally nothing is working and help would be much appreciated. Thanks in advance
推荐答案
以下是几种替代方法.
第三方 bitarray 库:
from bitarray import bitarray
a='010010'
b='000101'
logical_or_bitarray = bitarray(a) | bitarray(b) # output: bitarray('010111')
logical_or_string = ''.join(map(str, map(int, logical_or_bitarray))) # output: '010111'
Python字符串:-
Python strings:-
a='010010'
b='000101'
def compare_bits(A, B):
c_1 = str(int(A) | int(B))
c = (len(A) - len(c_1))*'0' + str(c_1)
return c
compare_bits(a, b)
这篇关于Python中位串的逻辑或的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!