在本文中,我們將學習如何在 Python 中將字元串轉換為其二進位等價物。
我們知道字元串是一個字元串序列,用引號表示。
二進位數的形式是 0 和 1,信息總是以二進位格式編碼,因為這是計算機理解的。
我們將在這裡使用的將字元串轉換為二進位的方法是使用 join(),order(),format()和 bytearray()。
我們應該獲取字元串中出現的字元的相應 ASCII 值,並將它們轉換為二進位。
讓我們看一下工具箱中的函數描述-
- join()- 它取所有的項,並將它們連接成一個實體(產生一個字元串)。
- order()-該方法取一個字元,並將其轉換為相應的 UNICODE 值。
- format()- 這個方法獲取一個值,並將其插入佔位符所在的位置,它也用於以指定的間隔合併字元串的各個部分。
- bytearray()- 它返回一個位元組數組。
下面的程序展示了如何做到這一點
示例-
# declaring the string
str_to_conv = "Let's learn Python"
# printing the string that will be converted
print("The string that we have taken is ",str_to_conv)
# using join() + ord() + format() to convert into binary
bin_result = ''.join(format(ord(x), '08b') for x in str_to_conv)
# printing the result
print("The string that we obtain binary conversion is ",bin_result)
輸出-
The string that we have taken is Let's learn Python
The string that we obtain binary conversion is 010011000110010101110100001001110111001100100000011011000110010101100001011100100110111000100000010100000111100101110100011010000110111101101110
解釋-
讓我們了解我們在上面的程序中做了什麼-
- 首先,我們已經用值「讓我們學習 Python」聲明了需要轉換為二進位的字元串。
- 下一步是顯示我們創建的字元串,以便在輸出的幫助下很容易理解哪一個是我們的字元串以及它的二進位等價物是什麼。
- 然後,我們使用了 format()方法,並將其參數指定為 order()和『08b』,這兩個參數使用
for
循環從字元串中獲取每個字元,並將它們轉換為二進位。 - 整個結果存儲在變數 bin_result 中,最後,我們顯示它的值。
在下一個示例中,我們將通過使用 bytearray()來做同樣的事情。
示例- 2
# declaring the string
str_to_conv = "Let's learn Python"
# printing the string that will be converted
print("The string that we have taken is ",str_to_conv)
# using join(), format() and bytearray() to convert into binary
bin_result = ''.join(format(x,'08b') for x in bytearray(str_to_conv,'utf-8'))
# printing the result
print("The string that we obtain binary conversion is ",bin_result)
輸出-
The string that we have taken is Let's learn Python
The string that we obtain binary conversion is 010011000110010101110100001001110111001100100000011011000110010101100001011100100110111000100000010100000111100101110100011010000110111101101110
示例-
讓我們看看上面的方法有多不同-
- 首先,我們已經用值「讓我們學習 Python」聲明了需要轉換為二進位的字元串。
- 下一步是顯示我們創建的字元串,以便在輸出的幫助下很容易理解哪一個是我們的字元串以及它的二進位等價物是什麼。
- 然後我們使用了 bytearray()函數,其中使用
for
循環獲取字元串中的每個字元,並將其轉換為二進位。 - 整個結果存儲在變數 bin_result 中,最後,我們顯示它的值。
原創文章,作者:VKCMI,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/126288.html