小编Nat*_*ate的帖子

.strip()方法不剥离神秘的空白字符

我正在从一个文件中读取一些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    '
Run Code Online (Sandbox Code Playgroud)

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

thing = b'hello\x00\x00\x00\x00'.decode('utf8').strip()
print(thing)
#the output is 'hello    '
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,尾随的nul字符没有被剥离 - 我认为这与.strip()无法识别的'\ x00'有关,但我看起来似乎认为它应该是.是什么赋予了?我怎样才能删除这些字符而不必做一些非常笨重的事情?

我找不到解决这个问题的帖子.

python string strip

1
推荐指数
1
解决办法
42
查看次数

标签 统计

python ×1

string ×1

strip ×1