We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
pycharm 重构常用快捷键
b''
''
""
bytes.decode()
str
str.encode()
bytes
replace()
utf-8
print(bytes)
利用 binascii 库,可以将 str 转为 十六进制,不过是保存在 bytes 中,我们如果要处理需要将 bytes 转为 str。
测试代码如下
if __name__ == '__main__': test = 'admin' print(type(test)) x = binascii.b2a_hex(test.encode('ascii')) print(type(x)) print(x) string = x.decode() print(type(string)) print(string) result = re.sub("(..)", r"0x\1 ", string, 0, re.MULTILINE) print(result)
运行结果
<class 'str'> <class 'bytes'> b'61646d696e' <class 'str'> 61646d696e 0x61 0x64 0x6d 0x69 0x6e
将形如 0x00 和 \x00 的字符串编码转换成 str 。
0x00
\x00
python 中的 十六进制 是 \x00, 使用之前得想转成 \x00 格式。
def to_bytes(data: str) -> str: data = data.replace('0x', '\\x') return str.encode(data, encoding='utf-8').decode() if __name__ == '__main__': data = '\x4D\x51\x54\x54' print(to_bytes(data=data))
def encode(s): return ' '.join([bin(ord(c)).replace('0b', '') for c in s]) def decode(s): return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]]) >>>encode('hello') '1101000 1100101 1101100 1101100 1101111' >>>decode('1101000 1100101 1101100 1101100 1101111') 'hello'
代码出处 https://segmentfault.com/q/1010000007305401
python 中 十六进制 是以 0x \x 开头
八进制是以 0o 开头
0o
二进制是以 0b 开头
0b
>>> hex(1024) '0x400' >>> bin(1024) '0b10000000000' >>> oct(1024) '0o2000'
>>> int('0x1024', 16) 4132 >>> bin(int('0x1024', 16)) '0b1000000100100' >>> oct(0x1024) '0o10044'
>>> int('1024', 8) 532 >>> hex(int('1024', 8)) '0x214' >>> bin(int('1024', 8)) '0b1000010100'
>>> int('1010', 2) 10 >>> oct(0b1010) '0o12' >>> hex(int('1010', 2)) '0xa'
我觉得看一下知乎上关于 Python 编码的讨论。https://www.zhihu.com/question/31833164
The text was updated successfully, but these errors were encountered:
No branches or pull requests
题外话
pycharm 重构常用快捷键
字符串和 bytes 区别
b''
包含''
或者""
包含bytes.decode()
转换成str
str.encode()
转换成bytes
replace()
...注意事项
bytes.decode()
可能会出错,因为utf-8
等编码可能无法解码一些字节print(bytes)
可以显示正常解码的部分str
和bytes
没有任何关系,不过你可以利用已有的方法将他们进行转换str 转 十六进制
利用 binascii 库,可以将 str 转为 十六进制,不过是保存在 bytes 中,我们如果要处理需要将 bytes 转为 str。
测试代码如下
运行结果
十六进制 转 str
将形如
0x00
和\x00
的字符串编码转换成str
。python 中的 十六进制 是
\x00
, 使用之前得想转成\x00
格式。str 二进制 互转
进制互转
python 中 十六进制 是以 0x \x 开头
八进制是以
0o
开头二进制是以
0b
开头十进制转十六进制,二进制,八进制
十六进制转十进制,八进制,二进制
八进制转十进制,十六进制,二进制
二进制转十进制,八进制,十六进制
我觉得看一下知乎上关于 Python 编码的讨论。https://www.zhihu.com/question/31833164
The text was updated successfully, but these errors were encountered: