How many bytes does the string have

Is there some kind of function that will tell me how many bytes a string in memory occupies?

I need to set the size of the socket buffer in order to pass the whole line at once.

+45
python
Oct 25 '10 at 9:20
source share
2 answers
import sys sys.getsizeof(s) # getsizeof(object, default) -> int # Return the size of object in bytes. 

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

+55
Oct 25 '10 at 9:23
source share

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




For example, ASCII characters use 1 byte each:

 >>> len("hello".encode("utf8")) 5 

while the Chinese use 3 bytes each:

 >>> len("你好".encode("utf8")) 6 
+52
Oct 25 '10 at 9:48
source share



All Articles