栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 字节字符串

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 字节字符串

python 字节字符串

Python字符串到字节 (Python String to bytes)

Python String to bytes conversion can be done in two ways:

Python字符串到字节的转换可以通过两种方式完成:

  1. Using bytes() constructor and passing string and encoding as argument.

    使用bytes()构造函数并将字符串和编码作为参数传递。
  2. Using encode() method on string object.

    在字符串对象上使用encode()方法。
Python字节到字符串 (Python bytes to String)

We can convert bytes to String using bytes class decode() instance method.

我们可以使用bytes类的decode()实例方法将字节转换为String。

Let’s look at examples of converting a string to bytes and then bytes to string in a python program.

让我们看一下在python程序中将字符串转换为字节然后将字节转换为字符串的示例。

s = 'abc'

# string to bytes using bytes()
b = bytes(s, encoding='utf-8')

print(type(b))
print(b)

# bytes to string using decode()
s = b.decode()
print('Original String =', s)

s = 'xyz'

# string to bytes using encode()
b = s.encode(encoding='utf-8')
print(b)

s = b.decode()
print('Original String =', s)

Output:

输出:


b'abc'
Original String = abc
b'xyz'
Original String = xyz
将字符串转换为字节的最佳方法 (Best way to convert a string to bytes)

Both the ways to convert a string to bytes are perfectly fine. String encode() and decode() method provides symmetry whereas bytes() constructor is more object-oriented and readable approach. You can choose any of them based on your preference.

将字符串转换为字节的两种方法都很好。 字符串encode()和decode()方法提供了对称性,而bytes()构造函数则更面向对象且更易读。 您可以根据自己的喜好选择其中任何一个。

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: str.encode() api doc, bytes.decode() api doc

参考: str.encode()api文档 , bytes.decode()api文档

翻译自: https://www.journaldev.com/23500/python-string-to-bytes-to-string

python 字节字符串

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/833637.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号