Python中字节对象与字符串

在Python2中,str和bytes都是相同的typeByte对象,而在Python3中定义的Byte对象是“ 字节序列 “类似于” unicode “Python 2中的对象。然而,字符串和字节对象有很多不同之处。其中一些描述如下: `

null
  • 字节对象是 字节 ,而字符串是 人物 .
  • 字节对象位于 机器可读 表单内部,字符串仅在 可读的 类型
  • 由于字节对象是机器可读的,所以它们可以 直接存储在磁盘上 .然而,字符串 需要编码吗 在此之前,它们可以存储在磁盘上。

string vs byte in python

有几种方法可以将字节对象转换为字符串,以及将字符串转换为字节对象。

编码

PNG、JPEG、MP3、WAV、ASCII、UTF-8等是不同形式的编码。编码是一种以字节表示音频、图像、文本等的格式。转换 字符串到字节 对象被称为编码。这是必要的,以便使用映射将文本存储在磁盘上 ASCII码 UTF-8 编码技术。 这项任务是通过使用 编码() .它以编码技术为依据。默认技术是“ UTF-8 “技术。

Python3

# Python code to demonstrate String encoding
# initialising a String
a = 'GeeksforGeeks'
# initialising a byte object
c = b 'GeeksforGeeks'
# using encode() to encode the String
# encoded version of a is stored in d
# using ASCII mapping
d = a.encode( 'ASCII' )
# checking if a is converted to bytes or not
if (d = = c):
print ( "Encoding successful" )
else : print ( "Encoding Unsuccessful" )


输出:

Encoding successful

解码

类似地,解码是一个转换信号的过程 字节对象到字符串 .它是使用 解码 。如果您知道使用哪种编码,字节字符串可以解码回字符串。编码和解码是 相反的 过程。

Python3

# Python code to demonstrate Byte Decoding
# initialising a String
a = 'GeeksforGeeks'
# initialising a byte object
c = b 'GeeksforGeeks'
# using decode() to decode the Byte object
# decoded version of c is stored in d
# using ASCII mapping
d = c.decode( 'ASCII' )
# checking if c is converted to String or not
if (d = = a):
print ( "Decoding successful" )
else : print ( "Decoding Unsuccessful" )


输出:

Decoding successful

本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享