Python中字符串转换为二进制

Python中字符串转换为二进制

在本文中,我们将学习如何将字符串转换为其二进制等效物。

我们知道字符串是一系列字符,用引号表示。

二进制数以0和1的形式存在,信息总是以二进制格式编码,因为这是计算机理解的格式。

我们在这里使用的将字符串转换为二进制的方法是使用join(),ord(),format()和bytearray()。

我们应该了解字符串中存在的字符的相应ASCII值并将其转换为二进制。

让我们来看一下我们在工具箱中使用的函数的描述-

  1. join()- 它将所有项目连接起来以形成单个实体(结果为单个字符串)。
  2. ord()- 此方法获取一个字符并将其转换为相应的UNICODE值。
  3. format()- 此方法获取一个值并将其插入到占位符所在的位置,还用于合并字符串的部分在指定的间隔处。
  4. 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

说明 –

让我们来理解一下我们在上面的程序中做了什么-

  1. 首先,我们声明了需要转换成二进制的字符串,其值为’让我们学习Python’。
  2. 下一步是显示我们创建的字符串,这样借助输出就能很容易地理解哪个是我们的字符串,它的二进制表示是什么。
  3. 然后,我们使用format()方法,并将ord()和’08b’指定为其参数,该方法使用for循环从我们的字符串中取出每个字符,并将其转换为二进制。
  4. 最终结果存储在变量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  

示例

让我们看看上述方法有多不同-

  1. 首先,我们声明了需要转换为二进制的字符串,其值为’让我们学习Python’。
  2. 接下来的步骤是显示我们创建的字符串,以便借助输出来理解哪个是我们的字符串及其二进制等效值。
  3. 然后,我们使用bytearray()函数,其中使用for循环逐个字符从字符串中取出并转换为二进制。
  4. 整体结果存储在变量bin_result中,最后我们显示其值。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程