繁体   English   中英

如何在python中实现str?

[英]How str implemented in python?

>>> import sys
>>> sys.getsizeof("")
40

为什么空字符串由如此多的字节组成? 有人知道这40个字节中存储了什么吗?

在Python中,字符串是对象,因此值是对象本身的大小。 所以这个大小总是比字符串大小本身大。

来自stringobject.h

typedef struct {
    PyObject_VAR_HEAD
    long ob_shash;
    int ob_sstate;
    char ob_sval[1];

    /* Invariants:
     *     ob_sval contains space for 'ob_size+1' elements.
     *     ob_sval[ob_size] == 0.
     *     ob_shash is the hash of the string or -1 if not computed yet.
     *     ob_sstate != 0 iff the string object is in stringobject.c's
     *       'interned' dictionary; in this case the two references
     *       from 'interned' to this object are *not counted* in ob_refcnt.
     */
} PyStringObject;

从这里你可以得到一些关于如何使用这些字节的线索:

  • len(str)+1个字节来存储字符串本身;
  • 散列的8个字节;
  • (......)

它给str类的对象大小赋予空值,当做sys.getsizeof("")这样的事情时,它实际上创建了一个具有许多属性的字符串类对象,然后计算该对象的大小。 它等于,

x = str()
sys.getsizeof(x)  #in my environment it prints 37

然后对于每个char它需要1个字节

x = "r"
sys.getsizeof(x)  #prints 38
x = "ros"
sys.getsizeof(x)  #prints 40

您可以在Laurent Luce博客文章中找到有关python字符串实现的一些信息。 此外,您可以浏览

字符串对象的大小取决于操作系统和机器类型以及一些选择。 在64位FreeBSD上,使用unicode进行字符串文字( from __future__ import unicode_literals ):

In [1]: dir(str)
Out[1]: ['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
 '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', 
'__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', 
'__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', 
'_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 
'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 
'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 
'swapcase', 'title', 'translate', 'upper', 'zfill']

In [2]: import sys

In [3]: sys.getsizeof("")
Out[3]: 52

In [4]: sys.getsizeof("test")
Out[4]: 68

In [7]: sys.getsizeof("t")
Out[7]: 56

In [8]: sys.getsizeof("te")
Out[8]: 60

In [9]: sys.getsizeof("tes")
Out[9]: 64

在这种情况下,每个字符额外使用4个字节。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM