简体   繁体   English

我如何转换python编码解码

[英]How do i convert python encode decode

Why are the results different?为什么结果不同?

# fabric
subject = run(openssl x509 -subject -noout -in signCert.pem)
subject = subject.split(b"CN = ")[1] # '\EC\A3\BC\EC\8B\9D\ED\9A\8C\EC\82\AC' <= type string

# FAIL
subject = '\EC\A3\BC\EC\8B\9D\ED\9A\8C\EC\82\AC'.replace('\\','\\x')
print(subject.encode('latin1').decode()) #\xEC\xA3\xBC\xEC\x8B\x9D\xED\x9A\x8C\xEC\x82\xAC

I want to decode like below我想解码如下

# Success

a = '\xEC\xA3\xBC\xEC\x8B\x9D\xED\x9A\x8C\xEC\x82\xAC'
print(a.encode('latin1').decode()) # 주식회사

How to convert this string?如何转换这个字符串? '\\EC\\A3\\BC\\EC\\8B\\9D\\ED\\9A\\8C\\EC\\82\\AC' -> b'\\xEC\\xA3\\xBC\\xEC\\x8B\\x9D\\xED\\x9A\\x8C\\xEC\\x82\\xAC' '\\EC\\A3\\BC\\EC\\8B\\9D\\ED\\9A\\8C\\EC\\82\\AC' -> b'\\xEC\\xA3\\xBC\\xEC\\x8B\\x9D\\xED\\x9A\\x8C\\xEC \\x82\\xAC'

One way to do what you're asking:做你问的一种方法:

s = '\EC\A3\BC\EC\8B\9D\ED\9A\8C\EC\82\AC'

result = eval('b"{}"'.format(s.replace("\\", "\\x")))

print(result)
print(result.decode())

Result:结果:

b'\xec\xa3\xbc\xec\x8b\x9d\xed\x9a\x8c\xec\x82\xac'
주식회사

However, it is likely that there's a better way to achieve this avoiding all the conversion, if you deal differently with the output from the run() command.但是,如果您以不同方式处理run()命令的输出,则可能有更好的方法来避免所有转换。

The reason the code above works is because it evaluates the new string as it would if the expression had been in code - which is what you're trying to do.上面的代码有效的原因是它评估新字符串,就像表达式已经在代码中一样 - 这就是你想要做的。

Another (safer) approach would be to split the string over backslashes, convert the hexadecimal into numerical values and construct a bytes object from that:另一种(更安全)的方法是将字符串拆分为反斜杠,将十六进制转换为数值并从中构造一个字节对象:

result2 = bytes(int(x, 16) for x in s[1:].split('\\'))

print(result2)
print(result2.decode())

Same result.结果一样。 This assumes you can be sure s starts with a backslash, hence the [1:] .这假设您可以确定s以反斜杠开头,因此[1:]

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

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