search

Home  >  Q&A  >  body text

python中字符串的按位或怎么实现?

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

a或b得到1000111001

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

黄舟黄舟2808 days ago868

reply all(1)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 17:46:08

    Code:

    1

    2

    3

    4

    5

    6

    7

    <code>a = "1000111000"

    b = "1000000001"

     

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

     

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

    </code>


    Result:

    1

    2

    <code>1000111001

    </code>


    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 < code>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: 🎜

    1

    2

    3

    4

    5

    <code>a = "1000111000"

    b = "1000000001"

     

    c = ''.join(str(int(ba) | int(bb)) for ba, bb in zip(a, b))

    print(c)</code>

    reply
    0
  • Cancelreply