0

I see python allows null characters in its strings. So it's implementation is not based on null-terminated string? But C only support null-terminated strings. Could anybody help explain how python string is implemented internally? And where is the soruce code in python that support this? Thanks.

>>> sys.stdout.write('x\0y')
xy>>>
user1424739
  • 11,937
  • 17
  • 63
  • 152
  • 1
    C and python are different languages. And for different languages different rules apply. – Jabberwocky Mar 01 '19 at 14:02
  • 4
    To be strict, C does not support any kind of strings. It only supports arrays of chars. It is the standard library that defines functions that depend on a string terminating with a `\0`. If you wanted you could define an own library that stores strings as a struct with a length and a pointer. Then you would no longer depend on the terminating zero. – RedX Mar 01 '19 at 14:03
  • 1
    @RedX also string literals are automatically NUL terminated. – Jabberwocky Mar 01 '19 at 14:06
  • Ok, that's true. But you could see it as a helping hand from the language to the library authors. – RedX Mar 01 '19 at 14:08
  • I added the source code question. The possible duplicate link does not provide any link to python source code. So this is not a duplicate. – user1424739 Mar 01 '19 at 14:11
  • [Python string objects implementation](http://laurentluce.com/posts/python-string-objects-implementation) explains the string object and some handling in detail. – jweyrich Mar 01 '19 at 14:16

1 Answers1

0

Strings in python are implemented as a class with various properties and methods. It probably allows nulls because the size of the string is explicitly stored.

In C, an string is just an array of characters terminated by a null byte. There's no data structure that keeps track of the size.

dbush
  • 205,898
  • 23
  • 218
  • 273