为什么Python的string.format pad不能用"\ x00"?

bon*_*ing 8 python string-formatting

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

测试用例:

>>> "{0:\x01<10}".format("bbb")
'bbb\x01\x01\x01\x01\x01\x01\x01'
Run Code Online (Sandbox Code Playgroud)

这表明十六进制转义字符通常起作用.

>>> "{0:\x00<10}".format("bbb")
'bbb       '
Run Code Online (Sandbox Code Playgroud)

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

>>> "{0:{1}<10}".format("bbb","\x00")
'bbb       '
>>> "{0:{1}<10}".format("bbb",chr(0))
'bbb       '
Run Code Online (Sandbox Code Playgroud)

甚至尝试了其他几种方法.

>>> "bbb" + "\x00" * 7
'bbb\x00\x00\x00\x00\x00\x00\x00'
Run Code Online (Sandbox Code Playgroud)

这有效,但不使用 string.format

>>> spaces = "{0: <10}".format("bbb")
>>> nulls  = "{0:\x00<10}".format("bbb")
>>> spaces == nulls
True
Run Code Online (Sandbox Code Playgroud)

Python显然代替了spaces(chr(0x20))而不是nulls(chr(0x00)).

cmd*_*cmd 0

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

我想答案是把它放在那里太方便了。

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