2 数据类型

12 阅读2分钟

1.数字类型

int(整形)

64位操作系统上,整数的位数为64位,取值范围为-2的63次方到2的63次方-1,即-9223372036854775808~9223372036854775807。

>>> type(1)  
<class 'int'>  

long(长整形) 

没有限制,但由于机器内存有限,我们使用的长整形数值不可能无限大。python2.2起,如果整数太大发生溢出,python会自动将整形转为长整形。python3里不再有长整形了,全是整形。

#python2  
>>> type(1111111111111111111111111111111111)  
<type 'long'>  
  
#python3  
>>> type(1111111111111111111111111111111111)  
<class 'int'>  

float(浮点型)

即小数,如 3.14。

>>> type(3.14)  
<class 'float'>  

2.字符串类型(str)

定义:在 python 中,加了引号(单,双,三)的字符,都被认为是字符串。
特性:不可修改;有索引可切片。

>>> name = 'ymf'  
>>> name[0]  
'y'  
>>> name[1]  
'm'  
>>> name[2]  
'f'  
>>> name[0:2]  #顾头不顾尾  
'ym'  

多行字符串:

>>> msg = '''Hello~  
... My name is mengfanyu,  
... My favorite food is candy,  
... and ice cream.  
... '''  
>>> msg  
'Hello~\nMy name is mengfanyu,\nMy favorite food is candy,\nand ice cream.\n'  
>>> print(msg)  
Hello~  
My name is mengfanyu,  
My favorite food is candy,  
and ice cream.  

字符串拼接:

>>> name = 'ymf'  
>>> food = 'candy'  
>>> name + ' like ' + food + ' !'  
'ymf like candy !'  

字符串内引用外部变量:

name = 'ymf'  
age = 13  
hobbie = 'candy'  
  
msg = '''  
----------xxx info----------  
name:xxx  
age:xxx  
hobbie:xxx  
-------------end-------------  
'''  
print(msg)  
  
----------xxx info----------  
name:xxx  
age:xxx  
hobbie:xxx  
-------------end-------------  
  
# 方式一:占位符(%s str;%d digit;%f float)  
name = 'ymf'  
age = 13  
hobbie = 'candy'  
  
msg = '''  
----------%s info----------  
name:%s  
age:%s  
hobbie:%s  
-------------end-------------  
'''%(name,name,age,hobbie)  
print(msg)  
  
# 方式二(python3支持):  
name = 'ymf'  
age = 13  
hobbie = 'candy'  
  
msg = f'''  
----------{name} info----------  
name:{name}  
age:{age}  
hobbie:{hobbie}  
-------------end-------------  
'''  
print(msg)  

3.布尔类型(bool)

- 就两个值,True(真)、False(假)。
- 用作程序中的逻辑判断。

>>> a = 3  
>>> b = 5  
>>> a < b  
True  
>>> a > b  
False  

4.列表(list)

>>> name_list = ["Zhao","Qian","Sun","Li"]  
>>> type(name_list)  
<class 'list'>  
  
#增  
>>> name_list  
['Zhao', 'Qian', 'Sun', 'Li']  
>>> name_list.append("Zhou")  
>>> name_list  
['Zhao', 'Qian', 'Sun', 'Li', 'Zhou']  
  
>>> name_list.insert(1,"Ymf")  
>>> name_list  
['Zhao', 'Ymf', 'Qian', 'Sun', 'Li', 'Zhou']  
  
#删  
>>> del name_list[5]  
>>> name_list  
['Zhao', 'Ymf', 'Qian', 'Sun', 'Li']  
  
>>> name_list.remove("Ymf")  
>>> name_list  
['Zhao', 'Qian', 'Sun', 'Li']  
  
#改   
>>> name_list[0] = "Zheng"  
>>> name_list  
['Zheng', 'Qian', 'Sun', 'Li']  
  
#查  
>>> name_list[1]  
'Qian'  
>>> name_list.index("Qian")  
1  
  
#切片  
>>> name_list  
['Zheng', 'Qian', 'Sun', 'Li']  
>>> name_list[0:2]           #顾头不顾尾  
['Zheng', 'Qian']  
  
>>> name_list[-3:-1]         #负数表示从右开始  
['Qian', 'Sun']  
  
>>> name_list[0:2:2]         #第三个数字表示步长,默认1  
['Zheng']  

5.其他数据类型

- 集合set:处理两组数据之间的关系
- 字典dict:存储更多信息,加快查询速度
- 字节bytes:二进制数据,处理图片、视频等