【问题标题】:How to remove the '\x0' from a python string?如何从 python 字符串中删除 '\x0'?
【发布时间】:2020-06-29 06:51:24
【问题描述】:
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',那么它也会删除所需的部分,并且对于任何其他情况也不起作用。我也尝试过使用替换功能。 请帮我解决这个问题。

【问题讨论】:

  • chr替换为str
  • 注意\x00是单个字符:print(len("\x00"))输出是1

标签: python string unicode binary xor


【解决方案1】:

chr 替换为str

  1. chrint 值中的单个字符串作为 ascii 代码。所以chr(0)表示ascii0字符,代表'\x00'
  2. 你想要的是str。它从给定的值生成字符串(在这种情况下为int)。 str(0)'0'

例子:

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

输出:

True
True
True
True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 2020-08-29
    • 2012-06-15
    • 2017-07-20
    • 1970-01-01
    相关资源
    最近更新 更多