tags:

views:

65

answers:

2

Is there some function which will tell me how many bytes does a string occupy in memory?

I need to set a size of a socket buffer in order to transfer the whole string at once.

+4  A: 
import sys
sys.getsizeof(s)

# getsizeof(object, default) -> int
# Return the size of object in bytes.

But actually you need to know its represented length, so something like len(s) should be enough.

eumiro
+1 for the function. Does this not return all the extra baggage to represent the object? The rest of the fields in the PyObject.
Noufal Ibrahim
@Noufal - exactly. For a simple 'a' string it returns 41.
eumiro
@eumiro: my 'a' needs 25 bytes; so either you run 64-bit Python or the font I use has simpler strokes :)
ΤΖΩΤΖΙΟΥ
Ignoring for the moment that `sys.getsizeof()` is utterly irrelevant to the OP's problem: a size of 25 or 41 is a nonsense; `malloc()` and friends usually allocate chunks of memory whose size is a multiple of `2 ** n` where `n` is certainly greater than 1, and some of the chunk is occupied by malloc overhead and `sys.getsizeof()` doesn't allow for any of this (because it doesn't know any details of the malloc implementation).
John Machin
+2  A: 

If it's a Python 2.x str, get its len. If it's a Python 3.x str (or a Python 2.x unicode), first encode to bytes (or a str, respectively) using your preferred encoding ('utf-8' is a good choice) and then get the len of the encoded bytes/str object.

ΤΖΩΤΖΙΟΥ