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)).