在Python3中将字符串转换为字节的最佳方法
要将字符串转换为字节,有多种方法,
方法1:使用encode()方法
test_str = "include_help" print(type(test_str)) test_bytes = test_str.encode() print(test_bytes) print(type(test_bytes))
输出结果
<class 'str'> b'include_help' <class 'bytes'>
在python3中,第一个参数encode()默认为'utf-8'。据推测,这种方法也更快,因为默认参数在C代码中导致NULL。
方法2:使用bytes()构造函数
test_str = "include_help" test_bytes_v2 = bytes(test_str, 'utf-8') print(type(test_bytes_v2)) print(test_bytes_v2)
输出结果
<class 'bytes'> b'include_help'
使用bytes构造函数提供的选项不仅仅是对字符串进行编码。但是,与使用构造函数相比,对字符串1进行编码比使用Python1具有更多的Python风格,因为它更具可读性。
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短