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