在Python3中将字符串转换为字节的最佳方法

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值