ホームページ >バックエンド開発 >Python チュートリアル >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>
Using '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 中国語 Web サイトの他の関連記事を参照してください。