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