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

来源:互联网 发布:淘宝客户要发票怎么办 编辑:程序博客网 时间:2024/06/05 11:30

本文均在 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 类型。

原创粉丝点击