Python str 与 bytes 类型(Python2/3 对 str 的处理)

时间:2023-03-09 07:31:59
Python str 与 bytes 类型(Python2/3 对 str 的处理)

本文均在 Python 3 下测试通过,python 2.x 会略有不同。

1. str/bytes

>> s = '123'
>> type(s)
str >> s = b'123'
bytes

2. str 与 bytes 之间的类型转换

python str与bytes之间的转换

str 与 bytes 之间的类型转换如下:

  • str ⇒ bytes:bytes(s, encoding='utf8')
  • bytes ⇒ str:str(b, encoding='utf-8')

此外还可通过编码解码的形式对二者进行转换,

  • str 编码成 bytes 格式:str.encode(s)
  • bytes 格式编码成 str 类型:bytes.decode(b)

3. strings 分别在 Python2、Python 3下

What is tensorflow.compat.as_str()?

Python 2 将 strings 处理为原生的 bytes 类型,而不是 unicode,

Python 3 所有的 strings 均是 unicode 类型。