[英]How to split String to int and bytestring literal
I have the following string: 我有以下字符串:
str = "3, b'\\\\xf3\\\\xc71\\\\xe9\\\\xad_\\\\xce\\\\x8bI\\\\x1c\\\\x04Y\\\\xd5z\\\\xa2Q'"
I need to split it in order to get two variables, an int and a bytestring like so: 我需要拆分它以获得两个变量,一个int和一个bytestring,如下所示:
number = 3
bytestring = b'\\xf3\\xc71\\xe9\\xad_\\xce\\x8bI\\x1c\\x04Y\\xd5z\\xa2Q'
What I tried doing: 我尝试做什么:
number, bytestring = [s for s in str.split(", ")]
int_number = int(number)
bytestring_in_bytes = bytestring.encode()
This unfortunately didn't work for the bytestring and I ended up with something like this: 遗憾的是,这对于bytestring并不起作用,我最终得到了这样的结果:
bytesring_in_bytes = b"b'\\\\xf3\\\\xc71\\\\xe9\\\\xad_\\\\xce\\\\x8bI\\\\x1c\\\\x04Y\\\\xd5z\\\\xa2Q'"
Any idea how to get the bytestring from the string? 知道如何从字符串中获取字节串吗?
What you here have seems like the textual representation (in Python the repr(..)
) of a bytestring. 你在这里看起来像是字节串的文本表示(在Python中的repr(..)
)。
You can use ast.literal_eval(..)
to convert this to a bytestring: 您可以使用ast.literal_eval(..)
将其转换为ast.literal_eval(..)
:
from ast import literal_eval
bytestring_in_bytes = literal_eval(bytestring)
Note that in case it contains a str
ing, int
, etc., then the type of bytestring_in_bytes
will be a str
, int
, etc. as well. 注意,如果它包含str
, int
等,那么bytestring_in_bytes
的类型也将是str
, int
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.