python 字节字符串
Python字符串到字节 (Python String to bytes)
Python String to bytes conversion can be done in two ways:
Python字符串到字节的转换可以通过两种方式完成:
- Using bytes() constructor and passing string and encoding as argument. 使用bytes()构造函数并将字符串和编码作为参数传递。
- 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()构造函数则更面向对象且更易读。 您可以根据自己的喜好选择其中任何一个。
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 字节字符串