Python 字节流、字符串、十六进制转换实例
在 Python 中,我们经常需要将字节流、字符串和十六进制之间相互转换,这在网络通信和加密算法中特别常见。Python 内置模块 binascii
和 bytes
提供了相应的函数,帮助我们完成这些转换。
bytes 和 str 之间的转换
Python 3 中的字符串是 Unicode 编码,而不是像 Python 2 那样的 ASCII 编码。所以,我们需要将字符串转换为 bytes 才能进行网络通信或者进行加密算法。如果我们想将字节流转换为字符串,则需要将字节流转换为 ASCII 码或其它字符集来实现。
将字符串转换为 bytes
我们可以通过 bytes()
或者 str.encode()
函数将字符串转换成 bytes。下面是两个示例:
# 使用 bytes() 函数将字符串转换为 bytes
s = "hello world"
b = bytes(s, encoding="utf8")
print(type(b)) # <class 'bytes'>
print(b) # b'hello world'
# 使用 str.encode() 函数将字符串转换为 bytes
s = "hello world"
b = s.encode("utf8")
print(type(b)) # <class 'bytes'>
print(b) # b'hello world'
在上面的代码中,我们首先将字符串 "hello world"
转换成了字节流 b'hello world'
,并打印输出了它们的类型和值。
将 bytes 转换为字符串
我们可以通过 str()
或者 bytes.decode()
函数将 bytes 转换成字符串。下面是两个示例:
# 使用 str() 函数将 bytes 转换成字符串
b = b"hello world"
s = str(b, encoding="utf8")
print(type(s)) # <class 'str'>
print(s) # hello world
# 使用 bytes.decode() 函数将 bytes 转换成字符串
b = b"hello world"
s = b.decode("utf8")
print(type(s)) # <class 'str'>
print(s) # hello world
在上面的代码中,我们首先将 bytes 对象 b'hello world'
转换成了字符串 "hello world"
,并打印输出了它们的类型和值。
字节流和十六进制的转换
将字节流转换为十六进制
我们可以通过 binascii.hexlify()
函数将字节流转换成十六进制表示。下面是一个示例:
import binascii
# 将字节流 b'hello world' 转换成十六进制
b = b"hello world"
hex_data = binascii.hexlify(b)
print(type(hex_data)) # <class 'bytes'>
print(hex_data) # b'68656c6c6f20776f726c64'
在上面的代码中,我们使用 Python 内置模块 binascii
中的 hexlify()
函数将字节流 b'hello world'
转换为了十六进制表示的 bytes 对象 b'68656c6c6f20776f726c64'
。
将十六进制转换为字节流
我们可以通过 binascii.unhexlify()
函数将 十六进制表示 转换为字节流的形式。下面是一个示例:
import binascii
# 将十六进制字符串 '68656c6c6f20776f726c64' 转换为字节流
hex_data = b"68656c6c6f20776f726c64"
b = binascii.unhexlify(hex_data)
print(type(b)) # <class 'bytes'>
print(b) # b'hello world'
在上面的代码中,我们使用 Python 内置模块 binascii
中的 unhexlify()
函数将十六进制的 bytes 对象 b'68656c6c6f20776f726c64'
转换为了字节流 b'hello world'
。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python 字节流,字符串,十六进制相互转换实例(binascii,bytes) - Python技术站