Python中str与bytes互相转换

2023-05-16

快速转换方式

# str to bytes
my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
type(my_str_as_bytes) # ensure it is byte representation
# bytes to str
my_decoded_str = my_str_as_bytes.decode()
type(my_decoded_str) # ensure it is string representation

另一种str to bytes方式:bytearray([source[, encoding[, errors]]])

If you look at the docs for bytes, it points you to bytearray:

bytearray([source[, encoding[, errors]]])

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.

The optional source parameter can be used to initialize the array in a few different ways:

If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().

If it is an integer, the array will have that size and will be initialized with null bytes.

If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

So bytes can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.

For encoding a string, I think that some_string.encode(encoding) is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding) -- there is no explicit verb when you use the constructor.

Edit: I checked the Python source. If you pass a unicode string to bytes using CPython, it calls PyUnicode_AsEncodedString, which is the implementation of encode; so you're just skipping a level of indirection if you call encode yourself.

Also, see Serdalis' comment -- unicode_string.encode(encoding) is also more Pythonic because its inverse is byte_string.decode(encoding) and symmetry is nice.

From: https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python中str与bytes互相转换 的相关文章

  • 使用sklearn宏f1-score作为tensorflow.keras中的指标

    我已经为tensorflow keras定义了自定义指标 以在每个时期之后计算宏f1分数 如下所示 from tensorflow import argmax as tf argmax from sklearn metric import
  • Jython - 使用 Spring,用 Python 编程?

    好吧 我在这方面完全是新手 所以 我知道 Spring 作为一个框架确实很好 而且我已经用 Python 编程有一段时间了 所以我想知道是否可以使用 Spring 框架但使用 Python 代码 我听说 Jython 可能是执行此操作的一个
  • 视频背景和按钮 - 移动

    我已经建立了this app http finnfrotscher pythonanywhere com on Flask 目前没有移动支持 由于视频加载时间相当长 因此我希望在手持设备上打开页面时提供相同的视频 但具有不同的分辨率 剪辑和
  • 如何使用Vault在Ansible中运行playbook api

    我有一本带有Vault的剧本 我可以运行它 ansible playbook info yml ask vault pass 现在 我想在 Ansible 中运行我的 playbook api 答案在如何使用Vault在Ansible v2
  • Python——“对象布局”

    有人可以描述以下异常吗 什么是 对象布局 以及它是如何定义的 谢谢 Traceback most recent call last File test gui py line 5 in
  • 如何在seaborn中记录比例

    我正在使用seaborn 绘制一些生物学数据 我想要一个基因相对于另一个基因的分布 在约 300 名患者中表达 并且以下代码工作正常 graph sns jointplot x Gene1 y Gene2 data data kind re
  • Django - 在设置中使用反向 url 映射

    例如 django 设置文件中的一些选项是 urlLOGIN URL and LOGIN REDIRECT URL 是否可以避免对这些 url 进行硬编码 而使用反向 url 映射 目前 这确实是我发现自己在多个地方编写相同网址的唯一地方
  • 在 pytest 中参数化并运行单个测试

    如何从配置了参数化的集合中运行单个测试 假设我有以下测试方法 pytest mark parametrize PARAMETERS LIST PARAMETERS VALUES def test my feature self param1
  • 如何在Python中使用x和y坐标验证ES384 JWT签名

    我有一个 JWT 如下 Authorization Bearer eyJhbGciOiJFUzM4NCIsInR5cCI6IkpXVCIsImtpZCI6IjQ0ODIzZjNkLTBiMDEtNGE2Yy1hODBlLWI5ZDNlOGE
  • 可以在 __getitem__ 上使用多个参数吗?

    我正在尝试使用 getitem self x y 在我的 Matrix 类上 但在我看来它不起作用 我仍然不太了解如何使用 python 我这样称呼它 print matrix 0 0 是否有可能使用多个参数 谢谢 也许我可以只使用一个参数
  • Python 元类有什么用?

    元类可以用其他方式做不到的事情做什么 Alex Martelli 表示 有些任务如果没有元类就无法完成Python 元类与类装饰器 https stackoverflow com questions 1779372 python metac
  • 如何使用 python 将威布尔分布拟合到数据?

    我正在寻找使用 Python 3 4 找到最适合一组数据的威布尔参数 import scipy stats as ss list1 list2 for x in range 0 10 list1 append ss exponweib pd
  • 如何在plotly dash应用程序中编写数学符号?

    我想在绘图破折号应用程序中绘制数学符号 例如 我尝试过这个 import dash import dash html components as html app dash Dash name app layout html Div chi
  • 包含多个双引号的 CSV 拆分正则表达式

    我有一个包含文本的 CSV 列数据 每行用双引号分隔 一行中的示例文本类似于此 notice 新行和每行之前的空格是故意的 Lorem ipsum dolor sit amet consectetur adipisicing elit se
  • Python Asyncio 子进程永远不会完成

    我有一个简单的 python 程序 我用它来测试带有子进程的 asyncio import sys time for x in range 100 print processing s 100 x sys stdout flush prin
  • 使用日期作为窗口函数实现 RANGE

    从 SQLAlchemy 1 4 25 开始 没有内置支持 所以我尝试使用该解决方案here https stackoverflow com a 69606048 11277108 这是我的复制 from datetime import d
  • 如何像 urllib 这样的模拟/存根 python 模块

    我需要测试一个需要使用 urllib urlopen 它也使用 urllib urlencode 查询外部服务器上的页面的函数 服务器可能宕机 页面可能发生变化 我不能依赖它进行测试 控制 urllib urlopen 返回内容的最佳方法是
  • pandas/numpy int64 中意外的 32 位整数溢出(python 3.6)

    让我从示例代码开始 import numpy from pandas import DataFrame a DataFrame nums 2233 23160 43608 a nums numpy int64 a nums print a
  • 如何通过python将python字典存储到mysql数据库中

    我试图通过将字典转换为字符串然后尝试插入来将以下字典存储到 mysql DB 中 但出现以下错误 如何解决这个问题 或者有其他方法将字典存储到 mysql DB 中吗 dic office component office Word2010
  • REQ/REP 模式中的 ZeroMQ FiniteStateMachineException

    我有两个简单的组件 它们应该使用 REQ REP ZeroMQ 模式相互通信 服务器 REP Socket 是使用 pyzmq 在 Python 中实现的 import zmq def launch server print Launchi

随机推荐