字符串有多少字节

时间:2022-11-15 00:04:52

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.

我需要设置套接字缓冲区的大小,以便一次传输整个字符串。

2 个解决方案

#1


57  

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.

但实际上你需要知道它的代表长度,所以像len(s)这样的东西就足够了。

#2


61  

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.

如果它是Python 2.x str,请获取它的len。如果它是Python 3.x str(或Python 2.x unicode),首先使用您的首选编码('utf-8'是一个不错的选择)编码为字节(或str),然后获取len编码的bytes / str对象。


For example, ASCII characters use 1 byte each:

例如,ASCII字符每个使用1个字节:

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

whereas Chinese ones use 3 bytes each:

而中国人每人使用3个字节:

>>> len("你好".encode("utf8"))
6

#1


57  

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.

但实际上你需要知道它的代表长度,所以像len(s)这样的东西就足够了。

#2


61  

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.

如果它是Python 2.x str,请获取它的len。如果它是Python 3.x str(或Python 2.x unicode),首先使用您的首选编码('utf-8'是一个不错的选择)编码为字节(或str),然后获取len编码的bytes / str对象。


For example, ASCII characters use 1 byte each:

例如,ASCII字符每个使用1个字节:

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

whereas Chinese ones use 3 bytes each:

而中国人每人使用3个字节:

>>> len("你好".encode("utf8"))
6