📜  Python|将字符串转换为字节

📅  最后修改于: 2022-05-13 01:55:13.844000             🧑  作者: Mango

Python|将字符串转换为字节

帧间转换像往常一样非常流行,但由于处理文件或机器学习(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 : 

方法 #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 :