简体   繁体   中英

Encode/decode specific character in string with hex notation using Python 2.7

How can I encode string 'banana', so that all a's become \\x97 like this?

b\x97n\x97n\x97

Then, how can I reverse or decode a string with embedded hex values back to the original string banana?

Use str.replace to replace that character with the hex representation of its ordinal value. And to get the actual string back you can decode it using string-decode .

>>> s = 'banana'
>>> print s.replace('a', '\\x' + format(ord('a'), 'x'))
b\x61n\x61n\x61
>>> print s.replace('a', '\\x' + format(ord('a'), 'x')).decode('string-escape')
banana

To do it and keep the encoding as standard ASCII not hex...

import re
s = 'banana'
t = s.replace('a', '\\x{}'.format(ord('a')))
subs = re.findall(r'\\x\d{2}',t)
decoded = ""
for match in set(subs):
    decoded = t.replace(match, chr(int(match[2:4]))
print decoded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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