Python 一个字符串有多少个字节

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4013230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:51:09  来源:igfitidea点击:

How many bytes does a string have

python

提问by Richard Knop

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.

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

采纳答案by eumiro

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)应该就足够了。

回答by tzot

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 lenof the encoded bytes/str object.

如果它是 Python 2.x str,请获取它的len. 如果它是 Python 3.x str(或 Python 2.x unicode),首先使用您的首选编码(bytesstr分别'utf-8'为 a )编码(是一个不错的选择),然后获取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