python基本數據類型


http://www.cnblogs.com/linjiqin/p/3608541.html

http://www.runoob.com/python3/python3-data-type.html

 

Python中的變量不需要聲明。每個變量在使用前都必須賦值,變量賦值以后該變量才會被創建。

在Python中變量就是變量,是內存地址指針,它沒有類型,我們所說的"類型"是變量所指的內存中對象的類型。類似於其他java、C中的引用類型。

Python3中有六個標准的數據類型:

字符串(String)
數字(Digit)
列表(List)
元組(Tuple)
集合(Sets)
字典(Dictionary)
日期(date)

 

一、字符串(String)

python中的字符串str用單引號('')或雙引號("")括起來,同時使用反斜杠(\)轉義特殊字符。

>>> s = 'Yes, he doesn\'t'
>>> print(s, type(s), len(s))
Yes, he doesn't <class 'str'> 15

如果不想讓\發生轉義,可以在字符串前面加r或R,表示原始字符串:

>>> print('C:\some\name')
C:\some
ame
>>> print(r'C:\some\name')
C:\some\name

另外,\可以作為紅續行符,表示下一行也是上一行的延續。還可以使用'''...'''或者"""..."""跨越多行。

字符串可以使用 + 運行符串連在一起,或者用 * 運算符重復:

注意:+連接字符串時,每連接一個時重新開辟內存,連接過多時,效率不高,這時候建議使用使用格式化字符串。

>>> s1 = 'we'
>>> s2 = 'are'
>>> s3 = 'go'
>>> print(s1 + ' ' + s2 + ' ' + s3)
we are go
>>>
>>> print("%s %s %s" % (s1, s2, s3))
we are go
>>>
>>> print('str' + 'ing', '*'*10)
string **********

python中的字符串有兩種索引方式,第一是從左往右,從0開始依次增加,第二種是從右往左,從-1開始依次減少。

注意!沒有單獨的字符類型,一個字符就是長度為1的字符串。

>>> word = 'Python'
>>> print(word[0], word[5])
P n
>>> print(word[-1], word[-6])
n P

還可以對字符串進行切片,獲取一段子串。用冒號分隔兩個索引,形式為 變量[頭下標:尾下標]

截取的范圍是半閉后開,並且兩個索引都可以省略:

>>> word = 'ILovePython'
>>>
>>>
>>> word[1:5]
'Love'

# 隔2個跳着取
>>> word[1:10:2]
'LvPto'
>>> word[:]
'ILovePython'
>>> word[5:]
'Python'
>>> word[-10:-6]
'Love'

與C字符串不同的是,python字符串不能被修改。如向一個索引位置賦值,word[0] = 'm' 會導致錯誤。

注意:

* 1、反斜杠可以用來轉義,使用r可以讓反斜杠不發生轉義。

* 2、字符串可以用 + 運算符連接在一起,用*運算符重復。

* 3、python中的字符串兩兩種索引方式,從左往右以0開始,從右往左以-1開始

* 4、Python中的字符串不能改變。

 

二、數字型(Numbers)

1、數字型以分類:int整型(Integer)、float浮點型、bool布爾型(boolean)、complex復數。

>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

 int

class int(object):
    """
    int(x=0) -> integer
    int(x, base=10) -> integer
    
    Convert a number or string to an integer, or return 0 if no arguments
    are given.  If x is a number, return x.__int__().  For floating point
    numbers, this truncates towards zero.
    
    If x is not a number or if base is given, then x must be a string,
    bytes, or bytearray instance representing an integer literal in the
    given base.  The literal can be preceded by '+' or '-' and be surrounded
    by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
    Base 0 means to interpret the base from the string as an integer literal.
    >>> int('0b100', base=0)
    4
    """
    def bit_length(self): # real signature unknown; restored from __doc__
        """
        int.bit_length() -> int
        
        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        6
        """
        return 0

    def conjugate(self, *args, **kwargs): # real signature unknown
        """ Returns self, the complex conjugate of any int. """
        pass

    @classmethod # known case
    def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
        """
        int.from_bytes(bytes, byteorder, *, signed=False) -> int
        
        Return the integer represented by the given array of bytes.
        
        The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
        
        The byteorder argument determines the byte order used to represent the
        integer.  If byteorder is 'big', the most significant byte is at the
        beginning of the byte array.  If byteorder is 'little', the most
        significant byte is at the end of the byte array.  To request the native
        byte order of the host system, use `sys.byteorder' as the byte order value.
        
        The signed keyword-only argument indicates whether two's complement is
        used to represent the integer.
        """
        pass

    def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
        """
        int.to_bytes(length, byteorder, *, signed=False) -> bytes
        
        Return an array of bytes representing an integer.
        
        The integer is represented using length bytes.  An OverflowError is
        raised if the integer is not representable with the given number of
        bytes.
        
        The byteorder argument determines the byte order used to represent the
        integer.  If byteorder is 'big', the most significant byte is at the
        beginning of the byte array.  If byteorder is 'little', the most
        significant byte is at the end of the byte array.  To request the native
        byte order of the host system, use `sys.byteorder' as the byte order value.
        
        The signed keyword-only argument determines whether two's complement is
        used to represent the integer.  If signed is False and a negative integer
        is given, an OverflowError is raised.
        """
        pass

    def __abs__(self, *args, **kwargs): # real signature unknown
        """ abs(self) """
        pass

    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass

    def __and__(self, *args, **kwargs): # real signature unknown
        """ Return self&value. """
        pass

    def __bool__(self, *args, **kwargs): # real signature unknown
        """ self != 0 """
        pass

    def __ceil__(self, *args, **kwargs): # real signature unknown
        """ Ceiling of an Integral returns itself. """
        pass

    def __divmod__(self, *args, **kwargs): # real signature unknown
        """ Return divmod(self, value). """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __float__(self, *args, **kwargs): # real signature unknown
        """ float(self) """
        pass

    def __floordiv__(self, *args, **kwargs): # real signature unknown
        """ Return self//value. """
        pass

    def __floor__(self, *args, **kwargs): # real signature unknown
        """ Flooring an Integral returns itself. """
        pass

    def __format__(self, *args, **kwargs): # real signature unknown
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass

    def __index__(self, *args, **kwargs): # real signature unknown
        """ Return self converted to an integer, if self is suitable for use as an index into a list. """
        pass

    def __init__(self, x, base=10): # known special case of int.__init__
        """
        int(x=0) -> integer
        int(x, base=10) -> integer
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is a number, return x.__int__().  For floating point
        numbers, this truncates towards zero.
        
        If x is not a number or if base is given, then x must be a string,
        bytes, or bytearray instance representing an integer literal in the
        given base.  The literal can be preceded by '+' or '-' and be surrounded
        by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
        Base 0 means to interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        4
        # (copied from class doc)
        """
        pass

    def __int__(self, *args, **kwargs): # real signature unknown
        """ int(self) """
        pass

    def __invert__(self, *args, **kwargs): # real signature unknown
        """ ~self """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lshift__(self, *args, **kwargs): # real signature unknown
        """ Return self<<value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    def __mod__(self, *args, **kwargs): # real signature unknown
        """ Return self%value. """
        pass

    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass

    def __neg__(self, *args, **kwargs): # real signature unknown
        """ -self """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __or__(self, *args, **kwargs): # real signature unknown
        """ Return self|value. """
        pass

    def __pos__(self, *args, **kwargs): # real signature unknown
        """ +self """
        pass

    def __pow__(self, *args, **kwargs): # real signature unknown
        """ Return pow(self, value, mod). """
        pass

    def __radd__(self, *args, **kwargs): # real signature unknown
        """ Return value+self. """
        pass

    def __rand__(self, *args, **kwargs): # real signature unknown
        """ Return value&self. """
        pass

    def __rdivmod__(self, *args, **kwargs): # real signature unknown
        """ Return divmod(value, self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __rfloordiv__(self, *args, **kwargs): # real signature unknown
        """ Return value//self. """
        pass

    def __rlshift__(self, *args, **kwargs): # real signature unknown
        """ Return value<<self. """
        pass

    def __rmod__(self, *args, **kwargs): # real signature unknown
        """ Return value%self. """
        pass

    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return value*self. """
        pass

    def __ror__(self, *args, **kwargs): # real signature unknown
        """ Return value|self. """
        pass

    def __round__(self, *args, **kwargs): # real signature unknown
        """
        Rounding an Integral returns itself.
        Rounding with an ndigits argument also returns an integer.
        """
        pass

    def __rpow__(self, *args, **kwargs): # real signature unknown
        """ Return pow(value, self, mod). """
        pass

    def __rrshift__(self, *args, **kwargs): # real signature unknown
        """ Return value>>self. """
        pass

    def __rshift__(self, *args, **kwargs): # real signature unknown
        """ Return self>>value. """
        pass

    def __rsub__(self, *args, **kwargs): # real signature unknown
        """ Return value-self. """
        pass

    def __rtruediv__(self, *args, **kwargs): # real signature unknown
        """ Return value/self. """
        pass

    def __rxor__(self, *args, **kwargs): # real signature unknown
        """ Return value^self. """
        pass

    def __sizeof__(self, *args, **kwargs): # real signature unknown
        """ Returns size in memory, in bytes """
        pass

    def __str__(self, *args, **kwargs): # real signature unknown
        """ Return str(self). """
        pass

    def __sub__(self, *args, **kwargs): # real signature unknown
        """ Return self-value. """
        pass

    def __truediv__(self, *args, **kwargs): # real signature unknown
        """ Return self/value. """
        pass

    def __trunc__(self, *args, **kwargs): # real signature unknown
        """ Truncating an Integral returns itself. """
        pass

    def __xor__(self, *args, **kwargs): # real signature unknown
        """ Return self^value. """
        pass

    denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the denominator of a rational number in lowest terms"""

    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the imaginary part of a complex number"""

    numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the numerator of a rational number in lowest terms"""

    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the real part of a complex number"""
View Code

 

2、布爾型(boolean)

bool只有兩個值 True 、False

>>> type(True)
<class 'bool'>
>>> type(False) >>> <class 'bool'> >>> bool(0) False >>> bool(1) True >>> bool(2) True >>> bool(3 == 3) True

 

 3、數值運算:

>>> 5 + 4  # 加法
9
>>> 4.3 - 2 # 減法
2.3
>>> 3 * 7  # 乘法
21
>>> 2 / 4  # 除法,得到一個浮點數
0.5
>>> 2 // 4 # 除法,得到一個整數
0
>>> 17 % 3 # 取余 
2
>>> 2 ** 5 # 乘方
32

注意:

* 1、python可以並行賦值,如 a, b = 1, 2

* 2、一個變量可以通過賦值指向不同類型的對象

* 3、數值的除法(/)問題返回一個浮點數,要獲取整數使用//運行符

* 4、在混合計算時,python會把整型轉換成浮點型。

 

4、數字類型轉換

int(x [, base])              將x轉換為一個整數
float(x)                     將x轉換為一個浮點數
complex(real [imag])         創建一個復數
str(x)                       將對象x轉換為字符串
repr(x)                      將x轉換為表達式字符串
eval(str1)                   用來計算在字符串中有效的python表達式,並返回一個對象
tuple(s)                     將序列s轉換為一個元組
list(s)                      將序列s轉換為一個列表
chr(x)                       將整數x轉換為一個字符
unichr(x)                    將整數x轉換為Unicode字符
ord(x)                       將一個字符轉換為它的整數值
hex(x)                       將一個整數轉換為一個十六進制字符串
oct(x)                       將一個整數轉換為一個八進制字符串
del(x)                       刪除變量x

數學函數 

函數 函數功能描述 示例 示例返回結果
abs(x) 返回數字的絕對值 abs(-10) 10
ceil(x) 返回數字的上入整數 math.ceil(4.1) 5
cmp(x, y)

比較x,y

x < y 返回 -1,

x == y 返回 0,

x > y 返回 1

   
exp      
       
       
       
       
       
       
       
       
       
       

 

 

 

 

 

 

 

 

 

 

 

 

三、列表(List)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM