python中字符串的按位或怎么实现?
黄舟
黄舟 2017-04-17 17:44:08
0
1
831

a="1000111000"
b="1000000001"
ab为字符串

a或b得到1000111001

除了一位一位的处理,有没有什么方便的方法

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
巴扎黑

Code:

a = "1000111000"
b = "1000000001"

c = int(a, 2) | int(b, 2)

print('{0:b}'.format(c))

Result:

1000111001

Analysis:

The operator | itself can perform bitwise operations, so we only need to know how to convert strings into binary integers and how to perform operations The complete integer result can be expressed as a 2-carry string. | 本身就可以執行 bitwise 的運算,所以我們只要知道如何將 字串 轉為 2進位整數 以及如何將運算完的 整數 結果以 2進位字串 表示即可.

int(a, 2) 可以將整數或字串 a 轉為2進位整數(精準來說應該是讓 a2進位 為基底進行整數轉換),接著利用 | 進行 bitwise or,最後 '{0:b}'.format(c)

int(a, 2) can convert the integer or string a into a binary integer (to be precise, let a be 2 carry is the basis for integer conversion), then use | to perform bitwise or, and finally '{0:b}'.format(c) method It allows us to format the value in binary format.

Other ideas

:

Interestingly, if we do it bit by bit, using generator comprehension plus some other functional programming style tricks can accomplish the task in a short one line: 🎜
a = "1000111000"
b = "1000000001"

c = ''.join(str(int(ba) | int(bb)) for ba, bb in zip(a, b))
print(c)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!