I need to fill the string with null characters ("\ x00"). I know many ways to do this, so please do not respond with alternatives. I want to know: why does Python's string.format() function not allow filling with zeros?
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" turns into space ("\ x20").
>>> "{0:{1}<10}".format("bbb","\x00") 'bbb ' >>> "{0:{1}<10}".format("bbb",chr(0)) 'bbb '
Even try a couple of other ways to do this.
>>> "bbb" + "\x00" * 7 'bbb\x00\x00\x00\x00\x00\x00\x00'
This works, but does not use string.format
>>> spaces = "{0: <10}".format("bbb") >>> nulls = "{0:\x00<10}".format("bbb") >>> spaces == nulls True
Python explicitly replaces spaces ( chr(0x20) ) instead of zeros ( chr(0x00) ).
python string-formatting
bonsaiviking
source share