幀間轉換像往常一樣非常流行,但由於處理文件或機器學習(Pickle 文件),我們廣泛要求將字符串轉換為字節,因此現在字符串到字節之間的轉換更為常見。讓我們討論一些可以執行此操作的方法。
方法#1:使用bytes(str, enc)
可以使用通用字節函數將字符串轉換為字節。此函數內部指向 CPython 庫,該庫隱式調用編碼函數以將字符串轉換為指定的編碼。
# Python code to demonstrate
# convert string to byte
# Using bytes(str, enc)
# initializing string
test_string = "GFG is best"
# printing original string
print("The original string:" + str(test_string))
# Using bytes(str, enc)
# convert string to byte
res = bytes(test_string, 'utf-8')
# print result
print("The byte converted string is :" + str(res) + ", type:" + str(type(res)))
輸出:
The original string:GFG is best The byte converted string is :b'GFG is best', type:<class 'bytes'>
方法#2:使用encode(enc)
執行此特定任務的最推薦方法是使用 encode 函數完成轉換,因為它減少了與特定庫的額外鏈接,該函數直接調用它。
# Python code to demonstrate
# convert string to byte
# Using encode(enc)
# initializing string
test_string = "GFG is best"
# printing original string
print("The original string:" + str(test_string))
# Using encode(enc)
# convert string to byte
res = test_string.encode('utf-8')
# print result
print("The byte converted string is :" + str(res) + ", type:" + str(type(res)))
輸出:
The original string:GFG is best The byte converted string is :b'GFG is best', type:<class 'bytes'>
相關用法
- Python Bytes轉String用法及代碼示例
- Python Bytes轉Int用法及代碼示例
- Python Int轉Bytes用法及代碼示例
- Python bytes()用法及代碼示例
- Python Bytearray轉Hexadecimal String用法及代碼示例
- Python list轉string用法及代碼示例
注:本文由純淨天空篩選整理自manjeet_04大神的英文原創作品 Python | Convert String to bytes。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。