如何删除那些“\ x00 \ x00”

时间:2016-08-10 21:02:43

标签: python string byte

如何删除字符串中的“\ x00 \ x00”? 我有很多这些字符串(如下所示)。我可以使用re.sub来替换那些“\ x00”。但我想知道是否有更好的方法可以做到这一点?在unicode,bytes和string之间进行转换总是令人困惑。

'Hello\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.

5 个答案:

答案 0 :(得分:16)

使用rstrip

>>> text = 'Hello\x00\x00\x00\x00'
>>> text.rstrip('\x00')
'Hello'

删除字符串末尾的所有\x00个字符。

答案 1 :(得分:16)

>>> a = 'Hello\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 
>>> a.replace('\x00','')
'Hello'

答案 2 :(得分:2)

我认为更通用的解决方案是使用:

cleanstring = nullterminatedstring.split('\x00',1)[0]

使用split作为分隔符\x00时间1字符串将split(...)[0]返回一个2元素列表:null之前的所有内容以及null之后的所有内容(它删除了分隔符)。附加'Hello\x00dpiecesofsomeoldstring\x00\x00\x00' 仅在第一个空(\ x00)字符之前返回字符串的一部分,我相信这是您正在寻找的内容。

某些语言中的约定,特别是类C语言,是指单个空字符标记字符串的结尾。例如,您还应该看到看起来像这样的字符串:

{{1}}

这里提供的答案将处理这种情况以及其他示例。

答案 3 :(得分:1)

基于提供的答案,我建议strip()在清除数据方面比rstrip()更通用,因为strip()从提供的字符串的开头和结尾删除了字符,而rstrip()只是删除了字符字符串末尾的字符。

但是,默认情况下,strip()不会将NUL字符视为空白,因此您需要明确指定。这可能会让您失望,因为print()当然不会显示NUL字符。我使用的解决方案是使用“ .strip().strip('\x00')”清理字符串:

>>> arbBytesFromSocket = b'\x00\x00\x00\x00hello\x00\x00\x00\x00'
>>> arbBytesAsString = arbBytesFromSocket.decode('ascii')
>>> print(arbBytesAsString)
hello
>>> str(arbBytesAsString)
'\x00\x00\x00\x00hello\x00\x00\x00\x00'
>>> arbBytesAsString = arbBytesFromSocket.decode('ascii').strip().strip('\x00')
>>> str(arbBytesAsString)
'hello'
>>>

这将为您提供所需的字符串,而不包含NUL字符。

答案 4 :(得分:0)

我尝试了 striprstrip,但它们不起作用,但这个起作用了; 使用 split 然后 join 结果 list:

if '\x00' in name:
    name=' '.join(name.split('\x00'))