简体   繁体   English

为什么空字符串在python中显示大小为49?

[英]Why does empty string show a size of 49 in python?

import sys
s = ""
print(sys.getsizeof(s))

output : 49 输出:49

What is the reason for this? 这是什么原因呢?

Because strings in Python are a certain type of object, they are not just a collection of enough characters to hold the string. 由于Python中的字符串是某种对象,因此它们不仅仅是容纳字符串的足够字符的集合。 As per the Python documentation, sys.getsizeof() will ... 根据Python文档, sys.getsizeof()将...

Return the size of an object in bytes. 返回对象的大小(以字节为单位)。

The size of the object may be larger for a variety of reasons, such as holding extra space for expansion without re-allocation, or having a minimum size. 出于各种原因,对象的大小可能会更大,例如,保留额外的扩展空间而无需重新分配,或者具有最小大小。 See, for example, PEP393 introduced in Python 3.3, which shows several (verbose) structures. 例如, PEP393 Python 3.3中引入的PEP393 ,它显示了几种(详细的)结构。

If you want the length of the string rather than the size of the internal object, I'm sure there's a function for that. 如果您要的是字符串的长度 ,而不是内部对象的大小,那么我确定有一个函数。 Maybe it's called len() :-) 也许它叫做len() :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么Python中的空字符串有时会占用49个字节,有时会占用51个字节? - Why does an empty string in Python sometimes take up 49 bytes and sometimes 51? 为什么 for 循环会在 python 中退出 for ""(空字符串)? - Why does for loop exit for "" (empty string) in python? 索引 49 超出轴 0 的范围,大小为 49 python numpy - Index 49 is out of bounds for axis 0 with size 49 python numpy 为什么在失败的int转换中此Python字符串的大小会更改 - Why does the size of this Python String change on a failed int conversion 为什么在Python中拆分一个空字符串时,split()返回一个空列表,而split('\n')返回['']? - When splitting an empty string in Python, why does split() return an empty list while split('\n') returns ['']? 为什么每个字符串都包含空字符串? - Why does every string contain the empty string? 为什么空字典的大小与Python中非空字典的大小相同? - Why is the size of an empty dict same as that of a non empty dict in Python? 为什么 Python IDLE 将 None 回显为空而不是字符串“None”(repr(None) 的值)? - Why does Python IDLE echo None as empty instead of string 'None' (the value of repr(None))? 为什么python允许没有“pass”语句的空函数(带有doc-string)主体? - Why does python allow an empty function (with doc-string) body without a “pass” statement? 为什么 Python 说我不能将字符串转换为整数,因为它有空字符串? - Why does Python say that I can't convert a string into an integer because it has empty strings?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM