您的位置:首页 > 编程语言 > Python开发

python基本数据类型

2016-01-29 14:46 711 查看
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: