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

Patricia Arquette
發布: 2024-10-25 05:59:02
原創
822 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!