import ctypes
a = 'abc'
b = ctypes.string_at(id(a), 3)
c = ctypes.string_at(id(a) + 20, 3)
I expect the result of b to be ‘abc’, but it is not; and the result of c is ‘abc’.
I don’t know why. Anyone can explain me?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Python, a
stris an object, so there is no guarantee about what it looks like in memory. Probably, it contains some more information, like the length of the string. In your case, the size of this “metadata” is apparently 20 bytes.Possibly, the object itself does not even contain the actual string, but rather a pointer to it. If that is the case, in your situation the actual string happens to be located 20 bytes after the object.
Either way, this is an implementation detail. None of this behaviour should be relied upon in any serious code.