python - 字符串到字节 Python
问题描述
我正在尝试将字符串转换为字节。该字符串包含一个整数,我必须将其转换为十六进制。例如: example : stringAddress = '32000' 我希望它变成 byte = b'\x7D\x00\x00
我的代码给了我 byte =b' \\
x7d \\
x00 \\
x00
当我尝试“替换”'\\'
字节更改时...在 b'}\x14\x00'
这是我的代码
from codecs import encode
numero = '32020'
numerohex = hex(int(numero))[2:]
print(numerohex)
if len(numerohex) == 4:
newnumero = r'\x{}\x{}\x00'.format(numerohex[:2], numerohex[2:4])
elif len(numerohex) == 3:
newnumero = r'\x0{}\x{}\x00'.format(numerohex[:1], numerohex[1:3])
elif len(numerohex) == 2:
newnumero = r'\x00\x{}\x00'.format(numerohex)
elif len(numerohex) == 1:
newnumero = r'\x00\x0{}\x00'.format(numerohex)
tmp = bytes(newnumero, encoding='raw_unicode_escape')
print(bytes(newnumero, encoding='raw_unicode_escape'))
print(encode(newnumero.encode().decode('unicode_escape'), "raw_unicode_escape"))
有人能帮我吗?
解决方案
推荐阅读
- javascript - 有没有办法通过使用 Netsuite 2.0 编写脚本来禁用事务列?
- java - 对象未使用 PageFactory.initElements(driver,class) 进行初始化;
- javascript - 如何将不完整的字符串索引到 JSON 键?
- java - 如何使用 snmp4j 发送带有 enginedId 的 v3 陷阱
- python-3.x - 在谷歌上检查多个用户的身份
- mysql - 如何在尝试添加外键时修复错误 1064
- html - 如何使用 Nebular 设置预选选项,nb-select
- python - 如何在 Django 模型表单中的 PasswordInput 上应用占位符属性?
- django - Django:精确查找的 QuerySet 值必须使用切片限制为一个结果
- c# - MongoDB 驱动程序不插入列表
C# 模型的属性作为数组