在本文中,我们将学习如何在 Python 中将字符串转换为其二进制等价物。
我们知道字符串是一个字符串序列,用引号表示。
二进制数的形式是 0 和 1,信息总是以二进制格式编码,因为这是计算机理解的。
我们将在这里使用的将字符串转换为二进制的方法是使用 join(),order(),format()和 bytearray()。
我们应该获取字符串中出现的字符的相应 ASCII 值,并将它们转换为二进制。
让我们看一下工具箱中的函数描述-
下面的程序展示了如何做到这一点
示例-
# 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
解释-
让我们了解我们在上面的程序中做了什么-
for
循环从字符串中获取每个字符,并将它们转换为二进制。在下一个示例中,我们将通过使用 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
示例-
让我们看看上面的方法有多不同-
for
循环获取字符串中的每个字符,并将其转换为二进制。本文链接:http://task.lmcjl.com/news/1058.html