Reputation: 11
import sys
s = ""
print(sys.getsizeof(s))
output : 49
What is the reason for this?
Upvotes: 0
Views: 985
Reputation: 882206
Because strings in Python are a certain type of object, they are not just a collection of enough characters to hold the string. As per the Python documentation, sys.getsizeof()
will ...
Return the size of an object in bytes.
The size of the object may be larger for a variety of reasons, such as holding extra space for expansion without re-allocation, or having a minimum size. See, for example, PEP393
introduced in Python 3.3, which shows several (verbose) structures.
If you want the length of the string rather than the size of the internal object, I'm sure there's a function for that. Maybe it's called len()
:-)
Upvotes: 2