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
?
这两个字符串之间的关系source
和output
>>> 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
解决方案
推荐阅读
- pine-script - 如何将 Pivot Points H/L 与 TradingView Pine 中的一条线连接起来?
- sql - 如何否定无效的订单数据?
- php - 替换文件中的单词,使用 PHP 中的另一个文件
- c++ - 运算符 [] 重载更新 2 个值 c++
- vba - Excel VBA 工作表更改事件导致消息框出现多次
- java - 为什么我们需要双重定义从 main 传递到方法的变量?
- javascript - Ajax 在新的 HTML 内容代码之后总是返回“1”
- angularjs - 如何增加帖子参数列表的大小
- javascript - 使用箭头键选择列表的子 li 元素
- xcode - Swift 4 - 表达式类型'@lvalue String?' 没有更多上下文是模棱两可的