如何从python字符串中删除“\x0”?

2024-06-26 14:48:09 发布

您现在位置:Python中文网/ 问答频道 /正文

def sxor(s1,s2):
    return ''.join(chr(ord(a) ^ ord(b)) for a,b in  zip (s1,s2))

text = sxor('a','a')
text

输出为

\x00

尝试了许多以前回答过的方法,但都无法删除“\x0”,因为只有“0”是必需的答案

这里还有一个例子:

def sxor(s1,s2):
    return ''.join(chr(ord(a) ^ ord(b)) for a,b in  zip (s1,s2))

text = sxor('1','2')

输出

\x03

我尝试过的事情:

def sxor(s1,s2):
    return ''.join(chr(ord(a) ^ ord(b)) for a,b in  zip (s1,s2))

text = sxor('1','1')
text.rstrip('\x0')

错误显示:


  File "<ipython-input-26-d4905edd1961>", line 6
    text.rstrip('\x0')
               ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-2: truncated \xXX escape

如果我把它写成“\x00”,那么它也会删除所需的部分,并且对任何其他情况都不起作用。我也尝试过使用replace函数。 请帮我解决这个问题


Tags: textinforreturndefzipjoinx00
1条回答
网友
1楼 · 发布于 2024-06-26 14:48:09

chr替换为str

  1. ^{}int值生成一个字符串作为ascii码。因此chr(0)表示ascii 0字符,表示为'\x00'
  2. 你想要的是^{}。它从给定的值(int在本例中)生成字符串str(0)'0'

示例:

print('\x00' == chr(0))
print('\x01' == chr(1))
print('0' == str(0))
print('1' == str(1))

输出:

True
True
True
True

相关问题 更多 >