简体   繁体   English

如何将 B 字符串转换为字节?

[英]How do I convert a B string to bytes?

bstr = "b'\\xe4\\xb8\\x96\\xe7\\x95\\x8c'"
bbytes = b'\\xe4\\xb8\\x96\\xe7\\x95\\x8c'

I want to convert bstr to bbytes , how can I do?我想将bstr转换为bbytes ,我该怎么做?

You can use the ast.literal_eval (documentation here ) function to evaluate this string as a python literal.您可以使用ast.literal_eval此处的文档)function 将此字符串评估为 python 文字。

import ast

bstr = "b'\\xe4\\xb8\\x96\\xe7\\x95\\x8c'"
bbytes = ast.literal_eval(bstr)
print(bbytes)  # Outputs: b'\xe4\xb8\x96\xe7\x95\x8c'

This function should be safe to use on user inputs (unlike eval ), though you should probably enforce a length limit to address the warning about crashing the interpreter with long/complex inputs.这个 function 应该可以安全地用于用户输入(与eval不同),尽管您可能应该强制执行长度限制以解决有关使用长/复杂输入导致解释器崩溃的警告。

Note this will also correctly parse other valid python literals (such as int , list , etc.), so if you want to enforce that you only end up with bytes you should check that, eg请注意,这还将正确解析其他有效的 python 文字(例如intlist等),因此如果您想强制您只以bytes结尾,您应该检查一下,例如

if not isinstance(bbytes, bytes):
  raise ValueError("Input must be a bytes string")

Hopefully you can change the input slightly, I changed the input to escape bstr so the special characters aren't evaluated immediately.希望您可以稍微更改输入,我将输入更改为转义bstr ,因此不会立即评估特殊字符。

If you're taking this string as user input, eg from input or from reading a file, this should already be the case.如果您将此字符串作为用户输入,例如来自input或读取文件,则应该已经是这种情况。

If you don't have a properly escaped input, you'll get an exception:如果您没有正确转义的输入,则会出现异常:

>>> bstr = "b'\xe4\xb8\x96\xe7\x95\x8c'"
>>> ast.literal_eval(bstr)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/ast.py", line 48, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/lib/python3.6/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
SyntaxError: bytes can only contain ASCII literal characters.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM