首页 > 解决方案 > 如何合并 0 或 1 的字符串,就好像我在 python 中的位域上做 OR 一样?

问题描述

例如,对于字符串“000100”、“010000”和“100000”,我希望结果为“110100”。

Python中有一个简单的方法吗?

标签: python

解决方案


You can convert each binary string to their actual integer value by using int(<str>, 2), then use the binary or operation (|) to merge them together and get the binary representation back by using bin:

>>> binstrings = ['000100', '010000', '100000']
>>> result = 0
>>> for s in binstrings:
...   result |= int(s, 2)
...
>>> result
52
>>> bin(result)
'0b110100'

推荐阅读