python有char类型吗?这篇文章来讲解char类型

很多小伙伴还不知道python有没有char类型 , 那么今天小编就通过这篇文章来给大家详细讲解一下在python中char类型的相关知识 , 这篇文章非常适合初学者进行阅读和学习 , 如果感兴趣的话一定要认真阅读完 。

python有char类型吗?这篇文章来讲解char类型

文章插图
那么python中到底有没有char类型呢?答案是python没有char类型 , 一个字符也是字符串 。那么为什么在Python中没有专门的char数据类型?
【python有char类型吗?这篇文章来讲解char类型】因为在Python中, 字符串中的每个字符占的空间大小是 8 bit , 简单胜于复杂 。
>>> import sys >>> sys.getsizeof('') 37 >>> sys.getsizeof('a') 38通过上面的例子我们可以看到 , 空字符占用37个byte , 长度为1的字符串a占用了38个 , 多了一个字符a之后又多了1个byte 。
其实 , 在Python的内部 , 字符串的实现是这样的 。
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;每个char就是存在 ob_sval 里面的 , 占大小8bit;余下的36个byte主要来自于宏PyObject_VAR_HEAD 。实际上python的string实现还用到了一个叫 interned的全局变量 , 里面可以存长度为0或1的字符串 , 也就是char , 可以节省空间并且加快速度 。
/* This dictionary holds all interned strings. Note that references to strings in this dictionary are *not* counted in the string's ob_refcnt. When the interned string reaches a refcnt of 0 the string deallocation function will delete the reference from this dictionary. Another way to look at this is that to say that the actual reference count of a string is: s->ob_refcnt + (s->ob_sstate?2:0) */ static PyObject *interned;实际上在 python 里既没有指针也没有"裸露的数据结构" (非对象), 连最简单的整数 integer 都是这样实现的 。
typedef struct { PyObject_HEAD long ob_ival; } PyIntObject;以上就是小编给大家带来的在python中的char类型相关知识了 , 希望大家通过阅读小编的文章之后能够有所收获!如果大家觉得小编的文章不错的话 , 可以多多分享给有需要的人 。

    推荐阅读