To convert a string to bytes, there are more than one way,
要将字符串转换为字节,有多种方法,
Approach 1: use encode() method
方法1:使用encode()方法
test_str = "include_help"
print(type(test_str))
test_bytes = test_str.encode()
print(test_bytes)
print(type(test_bytes))
Output
输出量
<class 'str'>
b'include_help'
<class 'bytes'>
In python3, the first parameter to encode() defaults to 'utf-8'. This approach is also supposedly faster because the default argument results in NULL in the C code.
在python3中, encode()的第一个参数默认为'utf-8' 。 据推测,这种方法也更快,因为默认参数在C代码中导致NULL。
Approach 2: use bytes() constructor
方法2:使用bytes()构造函数
test_str = "include_help"
test_bytes_v2 = bytes(test_str, 'utf-8')
print(type(test_bytes_v2))
print(test_bytes_v2)
Output
输出量
<class 'bytes'>
b'include_help'
Using the bytes constructor gives more options than just encoding the string. However, for encoding a string the approach1, is more pythonic than using a constructor, because it is more readable.
使用bytes构造函数提供了更多的选项,而不仅仅是对字符串进行编码。 但是,与使用构造函数相比,对字符串1进行编码比使用Python1具有更多的Python风格,因为它更具可读性。
翻译自: https://www.includehelp.com/python/best-way-to-convert-string-to-bytes-in-python3.aspx