Nat*_*ate 1 python string 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'有关,但我看起来似乎认为它应该是.是什么赋予了?我怎样才能删除这些字符而不必做一些非常笨重的事情?
我找不到解决这个问题的帖子.
NUL不是空格,所以strip()没有参数也不会剥离它们.您应该使用strip('\0'):
>>> 'hello\0\0\0\0'.strip('\0')
'hello'
Run Code Online (Sandbox Code Playgroud)