简体   繁体   English

如何将String拆分为int和bytestring文字

[英]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. 注意,如果它包含strint等,那么bytestring_in_bytes的类型也将是strint等。

暂无
暂无

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

相关问题 以10为底的int()的无效文字:“字符串” - invalid literal for int() with base 10: 'string' 以10为底的int()的无效文字:“字符串名称” - invalid literal for int() with base 10: 'string name' 如何在尝试捕获字符串时修复错误“无效的基础10的int()文字:'goelv'” - How to fix error “invalid literal for int() with base 10: 'goelv' ” when trying to capture string 当标识的值是一个字符串时,如何解决“以 10 为基数的 int() 的无效文字”错误 - How to resolve 'invalid literal for int() with base 10' error when the identified value is intended to be a string 将ContentType匹配为字符串,以10为底的int()获取无效的文字 - Matching ContentType as a string, get invalid literal for int() with base 10 Django IN查询作为字符串结果-以10为底的int()的无效文字 - Django IN query as a string result - invalid literal for int() with base 10 (Django)将字符串保存到EmailField会引发“以10为底的int()的无效文字” - (Django) saving string to EmailField raises 'invalid literal for int() with base 10' ValueError:int() 的无效文字,基数为 10:'SOME STRING' - ValueError: invalid literal for int() with base 10: 'SOME STRING' 查询字符串,错误为“ int()以10为底的无效文字” - Query String with error “invalid literal for int() with base 10” 基数为 10 的 int() 字面量:'testuser' 即使传递的参数是字符串 - literal for int() with base 10: 'testuser' even tho the argument passed is a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM