“二进制字符串”到b“二进制字符串”?,python-3.x"/>

首页 > 解决方案 > 如何转换“二进制字符串”到b“二进制字符串”?

问题描述

问题 - 找到convert_func()满足以下条件的

>>> source = '\xe6\x88\x91\xe5\x80\x91'
>>> output = b'\xe6\x88\x91\xe5\x80\x91'  # output = bytes('我們', 'utf8')
>>> assert convert_func(source) == output

如何定义一个convert_func可以将字符串从 转换source为的函数output

这两个字符串之间的关系sourceoutput

>>> type(source)
<class 'str'>
>>> type(output)
<class 'bytes'>
>>> source
'\xe6\x88\x91\xe5\x80\x91'
>>> output
b'\xe6\x88\x91\xe5\x80\x91'

source是 a ,但其<class str>内容(即\xe6\x88\x91\xe5\x80\x91)来自其二进制格式b'\xe6\x88\x91\xe5\x80\x91'(即output)。

方法尝试

我尝试使用source.encode('utf8'). 但是这种方法只适用于 ascii 字符。

>>> convert_func = lambda s: s.encode('utf8')

>>> output = 
>>> source = 'abcde'
>>> output = b'abcde'  # output = bytes('abcde', 'utf8')
>>> convert_func(source) == output
True

>>> source = '\xe6\x88\x91\xe5\x80\x91'
>>> output = b'\xe6\x88\x91\xe5\x80\x91'
>>> convert_func(source) == output
False

标签: python-3.x

解决方案


推荐阅读