Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Get size of string in bytes

Tags:

python

I have a string that is to be sent over a network. I need to check the total bytes it is represented in.

sys.getsizeof(string_name) returns extra bytes. For example for sys.getsizeof("a") returns 22 , while one character is only represented in 1 byte in python. Is there some other method to find this ?

like image 606
Iffat Fatima Avatar asked Jun 06 '15 19:06

Iffat Fatima


People also ask

How do you find the byte size of a string in Python?

If you want the size of the string in bytes, you can use the getsizeof() method from the sys module.

How do I find the byte size of a string?

1) s. length() will give you the number of bytes. Since characters are one byte (at least in ASCII), the number of characters is the same as the number of bytes.

How do I find the size of a string?

You can get the length of a string object by using a size() function or a length() function. The size() and length() functions are just synonyms and they both do exactly same thing.

What does bytes () do in Python?

Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.


1 Answers

If you want the number of bytes in a string, this function should do it for you pretty solidly.

def utf8len(s):     return len(s.encode('utf-8')) 

The reason you got weird numbers is because encapsulated in a string is a bunch of other information due to the fact that strings are actual objects in python.

Its interesting because if you look at my solution to encode the string into 'utf-8', there's an 'encode' method on the 's' object (which is a string). Well, it needs to be stored somewhere right? Hence, the higher than normal byte count. Its including that method, along with a few others :).

like image 136
Kris Avatar answered Sep 22 '22 17:09

Kris