迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

如何在 Python 中将字符串转换为字节 bytes

作者:迹忆客 最近更新:2023/02/28 浏览次数:

我们将介绍在 Python 3 中将字符串转换为字节的方法。

bytes 数据类型是从 Python 3 引入的内置类型,而 bytes 在 Python 2.x 中实际上是 string 类型,因此在在 Python 2.x 中我们不需要这种转换。

bytes 类构造函数从像字符串这样的数据构造字节数组。

bytes(string, encoding)

我们需要指定 encoding 参数,否则将引发 TypeError

>>> bytes("Test", encoding = "utf-8")
b'Test'
>>> bytes("Test")
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    bytes("Test")
TypeError: string argument without an encoding
str.encode(encoding=)

string 类的 encode 方法也可以将字符串转换为字节。与上述方法相比,它具有一个优点,即你如果你想要的 encodingutf-8 的话则不需要指定 encoding 参数。

>>> test = "Test"
>>> test.encode()
b'Test'
>>> test.encode(encoding="utf-8")
b'Test'

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便