我有一个Python变量(名为var),它包含具有以下文字数据的字符串:
day\r\n\\night在妖术中,它是:
64 61 79 5C 72 5C 6E 5C 5C 6E 69 67 68 74 07
d a y \ r \ n \ \ n i g h t BEL我只需要解码\\,\r和\n。
期望的输出(十六进制):
64 61 79 0D 0A 5C 6E 69 67 68 74 07
d a y CR LF \ n i g h t BEL使用decode不起作用:
>>> print(var.decode('ascii'))
AttributeError: 'str' object has no attribute 'decode'. Did you mean: 'encode'?使用regex查找和替换\\、\r和\n的转义值是不成功的,因为\night中的\n被视为0x0A。
是否可以指定我想要decode的字符,或者是否有更合适的模块?我正在使用Python3.10.2。
发布于 2022-03-28 07:10:09
感谢每一个给出答案的人,但他们似乎没有一个能完全解决我的问题。经过长时间的研究,我发现了这是sahil Kothiya的解决方案 (镜像) --我修改了它以解决我的具体问题:
import re, codecs
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\[\\nr] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
def decode_escapes(s):
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)无所事事的示威:

Notepad++中显示的特殊字符:

输出字符串的十六进制转储:

它甚至可以使用Unicode字符(我的脚本中的一个重要组件)。
无所事事的示威:

Notepad++中显示的特殊字符:

输出字符串的十六进制转储:

发布于 2022-03-27 11:40:36
找到类似的问题这里。根据这一点,您可以执行以下操作
var = r"day\r\n\\night"
# This is what you got previously
var.encode('ascii').hex()
# '64 61 79 5c 72 5c 6e 5c 5c 6e 69 67 68 74'
# To get required output do this
bytes(var, encoding='ascii').decode('unicode-escape').encode('ascii').hex()
# '64 61 79 0d 0a 5c 6e 69 67 68 74'发布于 2022-03-27 11:44:49
假设var是如下所示的字符串:
64617905C725C6E5C5C6E69676877407 (无空格)
你应该试着:
i = 0
escaped = {'72': '0D', '6E': '0A', '5C': '5C'}
while i < len(var):
if var[i:i+2] == '5C': # checks if the caracter is a '\'
i += 2 # if yes, goes to next character hex code in var
var[i-2:i+2] = escaped[var[i:i+2]] # replaces the '5Cxx' by its escaped value
i += 2它将将\r \n \\替换为相应的字符(CR LF \)。
稍后,我将在day\r\l\\night和64617905C725C6E5C5C6E696768774之间添加转换器。
编辑:转换器在这里!转换后的字符串每次都是r。
它处理input()的结果,但是对于硬编码的字符串,您必须输入:
var = 'day\\r\\l\\\\night'
这样代码就可以理解为'day',然后'\',然后'r',然后'\',然后'n',然后'\',然后'\',然后‘’,而不是'day',然后CR,然后‘LF,然后'\',然后’,然后‘’;
print(var)
会有印刷的
day\r\n\\night
而不是
day
\night# convert string to hex
r = ''
for c in var:
t = hex(ord(c))[2:]
if ord(c) < 16: t = '0' + t
r += t# convert hex to string
r = ''
c = 0
while c < len(var):
# transforms each hex code point into a decimal number
# I kind of cheat using `eval`. But don't worry. Doesn't matter.
# anyway, it then adds the corresponding character to `r`.
r += eval('chr(0x' + var[c:c+2] + ')') # does like, `r += chr(0x5C)` for example.
c += 2https://stackoverflow.com/questions/71635896
复制相似问题