How many bytes does a string have

Python

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichard KnopView Question on Stackoverflow
Solution 1 - PythontzotView Answer on Stackoverflow
Solution 2 - PythoneumiroView Answer on Stackoverflow