我正在从这样的文件中读取一些utf-8编码的数据:

with open (filename, 'rb') as f:
    bytes= f.read(offset, length)
    #bytes is b'hello\x00\x00\x00\x00'
    text = bytes.decode('utf-8')
    #text is 'hello    '
    stripped_text = text.strip()
    #stripped_text is 'hello    '


您可以使用以下简单的行来重新创建它

thing = b'hello\x00\x00\x00\x00'.decode('utf8').strip()
print(thing)
#the output is 'hello    '


如您所见,尾随的nul字符没有被剥离-我认为这与.strip()无法识别'\ x00'有关,但我似乎认为应该的所有地方都可以。是什么赋予了?如何删除这些字符而不必做一些笨拙的事情?

我找不到解决此问题的帖子。

最佳答案

NUL不是空格,因此不带参数的strip()不会删除它们。您应该改用strip('\0')

>>> 'hello\0\0\0\0'.strip('\0')
'hello'

关于python - .strip()方法不会删除神秘的空白字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52081810/

10-13 04:13