Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many bytes does a string have

Tags:

python

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.

like image 307
Richard Knop Avatar asked Oct 25 '10 09:10

Richard Knop


People also ask

How many bytes is a string Java?

An empty String takes 40 bytes—enough memory to fit 20 Java characters.

How many bytes are strings in C++?

The size of str is 22 bytes.

How many bits are in a string?

A byte is a string of 8 bits. A more compact way for us humans to write down long bit strings is to use hex form (hex is just notation; the bit string still consists of 0s and 1s inside the machine). The bit string is partitioned into groups of 4 bits each.

How much size does a string take?

In the current implementation at least, strings take up 20+(n/2)*4 bytes (rounding the value of n/2 down), where n is the number of characters in the string. The string type is unusual in that the size of the object itself varies.


1 Answers

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.


For example, ASCII characters use 1 byte each:

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

whereas Chinese ones use 3 bytes each:

>>> len("你好".encode("utf8")) 6 
like image 92
tzot Avatar answered Sep 29 '22 01:09

tzot