Home >Backend Development >Python Tutorial >Does Python have a char type?

Does Python have a char type?

步履不停
步履不停Original
2019-07-02 09:31:2013479browse

Does Python have a char type?

#Python does not have a char type, and a character is also a string.

Why is there no special char data type in Python?

Simple is better than complex. In Python, the space occupied by each character in the string is 8 bits.

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



As you can see, the null character occupies 37 bytes, and the length The string 'a' with a value of 1 occupies 38 bytes of memory. With one more character a, there is one more byte.

Inside Python, the string is implemented like this

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;

Each char is stored in ob_sval, accounting for 8 bits in size. The remaining 36 bytes mainly come from the macro PyObject_VAR_HEAD. In fact, python's string implementation also uses a global variable called *interned, which can store the length. A string of 0 or 1, that is, char, can save space and speed up.

/* 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;



In fact, there are neither pointers nor "nakedness" in Python "data structure" (non-object), even the simplest integer integer is implemented in this way

typedef struct {
PyObject_HEAD
long ob_ival;
} PyIntObject;



In short, this design satisfies python's "everything "It is an object" and the design philosophy is "everything should be as simple as possible".

Recommended related tutorials: Python video tutorial

The above is the detailed content of Does Python have a char type?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn