python 字节字符串_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:

输出:

<class 'bytes'>
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 字节字符串

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值