繁体   English   中英

从 Python 中的字符串中删除十六进制字符

[英]Remove hex character from string in Python

我正在尝试从字符串 o 十六进制值中删除一个字符,但我找不到解决方案来完成这项工作。 如果我打印 remove2 我得到字符串“\x41”,但是当我打印缓冲区时我得到 ABCD”。问题是我不明白为什么当我打印 remove2 时我得到字符串十六进制格式,而当我打印缓冲区时我得到ASCII 格式。我认为这是问题的根源。如何使用 Python 2 解决此问题?

>>> buffer = "\x41\x42\x43\x44"
>>> remove = raw_input("Enter hex value to remove: ")
Enter hex value to remove: 42
>>> remove2 = "\\x" + remove
>>> print buffer
ABCD
>>> print remove2
\x42
>>> buffer2 = buffer.replace(remove2, '')
>>> print buffer2
ABCD

我希望 buffer2 = "\x41\x43\x44"。

这是问题所在:

remove2 = "\\x" + remove

您不能以编程方式构建这样的转义序列。 相反,请执行以下操作:

remove2 = chr(int(remove, 16))

或者,您必须使buffer包含文字反斜杠而不是转义字符:

buffer = "\\x41\\x42\\x43\\x44"

问题是,如果你打印出没有打印的remove ,你会看到

>>> remove2
'\\x42'

\ 将留在那里而不是使其成为十六进制。 为此,您需要这样做:

remove.decode('hex')

所以代码是:

>>> buffer = "\x41\x42\x43\x44"
>>> remove = raw_input("Enter hex value to remove: ")
Enter hex value to remove: 42
>>> remove2=remove.decode('hex')
>>> buffer.replace(remove2, '')
'ACD'

这是否有助于/回答您的问题?

您将需要转义缓冲区字符串中的\ o/w 它将被视为十六进制值。 所以,

>>> buffer="\\x41\\x42\\x43"`<br>
>>> remove = "42"`<br>
>>> remove = "\\x" + remove` <br>
>>> buffer = buffer.replace(remove, '')` <br>
>>> print buffer #prints \\\x41\\\x43

您可以使用filter()并使用用户输入的“42”和原始字节(在 Python2 中只是一个字符串)构造一个过滤后的字节 object。

>>> inp = "42"
>>> filter(lambda x: x != chr(int(inp, 16)), 'ABCD')
'ACD'

Python 3

>>> inp = "42"
>>> bytes(filter(lambda x: x != int(inp, 16), b'ABCD'))
b'ACD'

无论如何,使用replace()更简单,这只是从字节 object 中过滤掉特定值的另一种方法。 它说明了其他答案指出的基本思想。 用户输入需要正确转换为您要删除的值。

当 interp 呈现 output 时,对于对应于 utf-8 或 ascii 可打印字符的字符/值,反斜杠不会以字节或 str 对象表示。 如果没有对应的可打印字符,则该值的转义版本将显示在 output 中。

暂无
暂无

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

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