new string method in 2.5 (partition)

Duncan Booth duncan.booth at invalid.invalid
Fri Sep 22 04:27:49 EDT 2006


Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> wrote:

> In message <mailman.354.1158791333.10491.python-list at python.org>, Gabriel
> Genellina wrote:
> 
>> ... a python string has both a length *and* a null terminator (for
>> ease of interfacing C routines ...
> 
> How does that work for strings with embedded nulls? Or are the C routines
> simply fooled into seeing a truncated part of the string?
> 
If passed to a C library function it would mean that the C code would 
generally only use up to the first embedded null. However the Python 
standard library will usually check for nulls first so it can throw an 
error:

>>> with open('test.txt', 'r') as f:
...     print f.read()
...
Hello world

>>> with open('test.txt\x00junk', 'r') as f:
...     print f.read()
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: file() argument 1 must be (encoded string without NULL 
bytes), not str
>>>

What actually happens is that Python argument parsing code will reject 
values with embedded nulls if asked to convert a parameter to a C string 
('s', 'z', 'es', or 'et' formats), but will allow them if converting to a C 
string and a length ('s#', 'z#', 'es#', or 'et#').



More information about the Python-list mailing list