首頁  >  文章  >  後端開發  >  如何在 Python 中將字串轉換為二進位?

如何在 Python 中將字串轉換為二進位?

Patricia Arquette
Patricia Arquette原創
2024-10-25 05:59:02823瀏覽

How to Convert a String to Binary in Python?

在Python 中將字串轉換為二進位

在Python 中,有多種方法將字串轉換為其二進位表示法。

使用 'ord' 函數:

此方法使用 ord() 函數取得字串中每個字元的 Unicode 程式碼點。然後使用 format() 函數將程式碼點轉換為二進位。

<code class="python">import functools

def toBinary(st):
    return ' '.join(format(ord(x), 'b') for x in st)</code>

使用 'bytearray':

或者,您可以使用 Python 的 bytearray 類別將字串表示為位元組序列。然後可以使用 format() 函數將每個位元組轉換為二進位。

<code class="python">def toBinary(st):
    return ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))</code>

這是一個例子:

<code class="python">st = "hello world"
print(toBinary(st))
# OR
print(' '.join(format(ord(x), 'b') for x in st))
# Output: 1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100</code>

以上是如何在 Python 中將字串轉換為二進位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn