溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python中有沒有char類型

發布時間:2020-11-11 14:31:53 來源:億速云 閱讀:292 作者:小新 欄目:編程語言

小編給大家分享一下python中有沒有char類型,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

python沒有char類型,一個字符也是字符串。

為什么在Python中沒有專門的char數據類型呢?

簡單勝于復雜。在 Python 中, 字符串中的每個字符占的空間大小是 8 bit.

>>> import sys
>>> sys.getsizeof('')
37
>>> sys.getsizeof('a')
38



可以看到, 空字符占用37個 byte, 長度為1的字符串 'a' 占內存 38個 byte. 多了一個字符 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 的 "一切都是對象", "一切都盡可能simple" 的設計思想。

以上是python中有沒有char類型的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女