本文介绍了为什么 Python 的 string.format 不能用“\x00"填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用空字符(\x00")填充一个字符串.我知道很多方法可以做到这一点,所以请不要用替代方案来回答.我想知道的是:为什么 Python 的 string.format() 函数不允许用空值填充?

测试用例:

>>>"{0:\x01

这表明十六进制转义字符通常有效.

>>>"{0:\x00

但是\x00"变成了一个空格(\x20").

>>>"{0:{1}<10}".format("bbb","\x00")'bb'>>>"{0:{1}<10}".format("bbb",chr(0))'bb'

甚至尝试其他几种方法.

>>>"bbb" + "\x00" * 7'bbb\x00\x00\x00\x00\x00\x00\x00'

这有效,但不使用 string.format

>>>空格 = "{0: <10}".format("bbb")>>>nulls = "{0:\x00

Python 显然用空格(chr(0x20))代替空值(chr(0x00)).

解决方案

因为 Python2.7 中的 string.format 方法是 Python3 string.format 的反向移植.Python2.7 unicode 是 Python 3 字符串,其中 Python2.7 字符串是 Python3 字节.字符串是在 Python3 中表达二进制数据的错误类型.您将使用没有格式方法的字节.所以你真的应该问,为什么 format 方法在 2.7 中是字符串,而它应该只在 unicode 类型上,因为那是 Python3 中的字符串.

我猜答案是把它放在那里太方便了.

作为一个相关的问题,为什么还没有format 字节

I wanted to pad a string with null characters ("\x00"). I know lots of ways to do this, so please do not answer with alternatives. What I want to know is: Why does Python's string.format() function not allow padding with nulls?

Test cases:

>>> "{0:\x01<10}".format("bbb")
'bbb\x01\x01\x01\x01\x01\x01\x01'

This shows that hex-escaped characters work in general.

>>> "{0:\x00<10}".format("bbb")
'bbb       '

But "\x00" gets turned into a space ("\x20").

>>> "{0:{1}<10}".format("bbb","\x00")
'bbb       '
>>> "{0:{1}<10}".format("bbb",chr(0))
'bbb       '

Even trying a couple other ways of doing it.

>>> "bbb" + "\x00" * 7
'bbb\x00\x00\x00\x00\x00\x00\x00'

This works, but doesn't use string.format

>>> spaces = "{0: <10}".format("bbb")
>>> nulls  = "{0:\x00<10}".format("bbb")
>>> spaces == nulls
True

Python is clearly substituting spaces (chr(0x20)) instead of nulls (chr(0x00)).

解决方案

Because the string.format method in Python2.7 is a back port from Python3 string.format. Python2.7 unicode is the Python 3 string, where the Python2.7 string is the Python3 bytes. A string is the wrong type to express binary data in Python3. You would use bytes which has no format method. So really you should be asking why is the format method on string at all in 2.7 when it should have really only been on the unicode type since that is what became the string in Python3.

Which I guess that answer is that it is too convenient to have it there.

As a related matter why there is not format on bytes yet

这篇关于为什么 Python 的 string.format 不能用“\x00"填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:24