什么是数据类型?
计算机不能区分数字和字符的区别,需要我们去告诉他,于是就有了数据类型
数字
int(整型)
在64位系统上,整数的位数为64位,取值范围为2^63~2^63-1,即-9223372036854775808~9223372036854775807
>>> a = 2**64 >>> type(a) <class 'int'> >>> b = 2**60 >>> type(b) <class 'int'>
bool()
>>>bool() # 无参数时返回False False >>> bool(0) # 0是False False >>> bool(1) True >>> bool(2) True >>> issubclass(bool, int) # bool 是 int 子类 True
float (浮点型)
即小数
>>> n = 2.3 >>> type(n) <class 'float'>
字符串(str)
定义
字符串是一个有序的字符的集合,用于存储和表示基本的文本信息,在Python中,加了引号的字符都被认为是字符串!
>>> name = "Alex Li" #双引号 >>> age = "22" #只要加引号就是字符串 >>> age2 = 22 #int >>> >>> msg = '''My name is Alex, I am 22 years old!''' #3个引号也可以 >>> >>> hometown = 'ShanDong' #单引号也可以
在下面这种情况,使用单双引号
msg = "My name is Alex , I'm 22 years old!"
多行字符串必须用多引号
msg = ''' 为你我受冷风吹 寂寞时候流眼泪 有人问我是与非 说是与非 可是谁又真的关心谁 若是爱已不可为 你明白说吧无所谓 不必给我安慰 何必怕我伤悲 就当我从此收起真情 谁也不给 ''' print(msg)
特性
-
按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序
-
-
可以进行切片操作
-
不可变,字符串是不可变的,不能像列表一样修改其中某个元素,所有对字符串的修改操作其实都是相当于生成了一份新数据。
取消字符的特殊意义
字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加
>>> names = 'th\nth' >>> print(names) th th >>> names = r'th\nth' >>> print(names) th\nth
简单拼接
>>> name 'Alex Li' >>> age '22' >>> >>> name + age #相加其实就是简单拼接 'Alex Li22' >>> >>> name * 10 #相乘其实就是复制自己多少次,再拼接在一起 'Alex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex Li'
注意,字符串的拼接只能是双方都是字符串,不能跟数字或其它类型拼接
>>> type(name),type(age2) (<type 'str'>, <type 'int'>) >>> >>> name 'Alex Li' >>> age2 22 >>> name + age2 Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'int' objects# 错误提示数字 和 字符 不能拼接
常用操作
def capitalize(self):
>>> name = 'aaaa' >>> name.capitalize() 'Aaaa' # 首字母大写
def casefold(self):
>>> c = 'Alex Li' >>> c.casefold() 'alex li' # 把字符串全变小写
def center(self, width, fillchar=None):
>>> c.center(50, "-") '---------------------Alex Li----------------------' # 居中显示,第一个数值表示宽度,第二个数值表示补充的字符
def count(self, sub, start=None, end=None):
>>> s = "welcome to apeland" # 查找元素个数 >>> s.count('e') # 查找'e'个数 3 >>> s.count('e',3) # 查找e个数,从下标为3的位置开始 2 >>> s.count('e',3,-1) # 查找e个数,从下标为3的位置开始,到下标为-1时结束 2
def endswith(self, suffix, start=None, end=None):
>> > s = "welcome to apeland" >> > s.endswith("land") # 判断以什么结尾 True
def find(self, sub, start=None, end=None):
>>> s = "welcome to apeland" >>> s.find('e') # 找e,返回下标 1 >>> s.find('e',2) # 从索引2开始找e 6 >>> s.find('e',7,-5) # 在7和-5之间找e -1 # 没找到,返回-1
def index(self, sub, start=None, end=None):
>>> s = "welcome to apeland" >>> s.index('e') # 找e,返回下标 1 >>> s.index('e',2) # 从2开始,找e,返回下标 6 >>> s.index('e',7,-5) # 在7和-5之间找e Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found # 找不到抛出valueError异常
def format(self, *args, **kwargs):
>> > s = "Welcome {0} to Apeland,you are No.{1} user." >> > s.format("Eva", 9999) # 第零个元素是对应{0},第一个元素是对应{1} 'Welcome Eva to Apeland,you are No.9999 user.' >> > s1 = "Welcome {name} to Apeland,you are No.{user_num} user." >> > s1.format(name="Alex", user_num=999) # 不用0、1,直接用=连接 'Welcome Alex to Apeland,you are No.999 user.' # 类似占位符
def isdigit(self):
>>> num = '123' >>> num.isdigit() # 判断是不是整数 True #是整数返回True >>> s = "welcome to apeland" >>> s.isdigit() False # 不是整数返回False >>> nume = '12.1' >>> nume.isdigit() False # 小数也返回False # 需要用户输入整数时,先判断是否是整数,再把字符创强行转换成整型
def islower(self):
>>> s = "welcome to apeland" >>> s.islower() # 判断都是小写 True # 都是小写返回True,不都是返回False
def isspace(self):
>>> asd = ' ' >>> asd.isspace() # 判断是不是空格,只有空格才返回True True >>> asd = 'asd' >>> asd.isspace() False
def isupper(self):
>>> asd = 'ASD' >>> asd.isupper() # 判断都是大写 True # 都是大写返回True >>> asd = 'asd' >>> asd.isupper() False
def join(self, iterable):
>>> n = ['alex','jack','rain'] >>> '|'.join(n) # 多个字符串用拼接起来,中间是“|” 'alex|jack|rain' # 只能拼接字符串,不能拼接数字 # 其中n = set 时,拼接key
def ljust(self, width, fillchar=None):
>>> asd = 'asd' >>> asd.ljust(10,'!') # 从左开始数,数到 width,不够的在后面补 fillchar 'asd!!!!!!!'
def rjust(self, width, fillchar=None):
>>> asd = 'asd' >>> asd.rjust(10,'!') # 从右开始数,数到 width,不够的在前面补 fillchar '!!!!!!!asd'
def lower(self):
>>> asd = 'ASD' >>> asd.lower() # 把所有字母变成小写 'asd'
def upper(self):
>>> asd = 'asd' >>> asd.upper() # 把所有字母改成大写 'ASD'
def strip(self, chars=None):
>>> asd = ' \nasd\t ' >>> asd.strip() # 去掉两边的空格和\n,\t等 'asd'
def lstrip(self, chars=None):
>>> asd = ' \nasd\t ' >>> asd.lstrip() # 去掉左边的空格和\n,\t等 'asd\t '
def rstrip(self, chars=None):
>>> asd = ' \nasd\t ' >>> asd.rstrip() # 去掉右边的空格和\n,\t等 ' \nasd'
def replace(self, old, new, count=None):
>>> asd = 'asd 120 , zxc 120 , qwe 20' >>> asd.replace('120','20') # 把字符 120 替换成字符 20 'asd 20 , zxc 20 , qwe 20' >>> asd.replace('20','120',2) # 把字符20 替换成字符 120 ,而且替换次数不超过2 'asd 1120 , zxc 1120 , qwe 20'
def rsplit(self, sep=None, maxsplit=-1):
>>> s 'welcome to apeland' >>> s.rsplit(' ') # 以" "为分隔符,从右边开始分割 # 如果是s.rsplit( ),则包含\n、\t ['welcome', 'to', 'apeland'] >>> s.rsplit('e') # 以"e"为分隔符,从右边开始分割 ['w', 'lcom', ' to ap', 'land'] >>> s.rsplit('e',2) # 以"e"为分隔符,从右边开始分割,分割2次 ['welcom', ' to ap', 'land']
def split(self, sep=None, maxsplit=-1):
>>> s 'welcome to apeland' >>> s.split('e',2) # 从左边开始以e为分隔符开始切割,切割2次,即形成3个子字符串 ['w', 'lcom', ' to apeland']
def startswith(self, prefix, start=None, end=None):
>>> s 'welcome to apeland \nasd\tqwer' >>> s.startswith('st') # 判断从 st 开始 False >>> s.startswith('wel') # 判断是从 wel 开始 True >>> s.startswith('el',1) #从 索引1 开始,判断是从 el 开始 True
def swapcase(self):
>>> asd = 'aaAAaa' >>> asd.swapcase() # 大小写互换 'AAaaAA'
def zfill(self, width):
>>> aaa = 'aaa' >>> aaa.zfill(10) # 指定宽度10,不够的用零补,补在前面 '0000000aaa'
列表(list)
定义
[]内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素
>>> na = [12,23,34,'asd'] >>> na [12, 23, 34, 'asd']
特点
1.可存放多个值
2.按照从左到右的顺序定义列表元素,下标从0开始顺序访问,有序

3.可修改指定索引位置对应的值,可变
列表的操作
增加操作
追加
>>> names ['alex', 'jack'] >>> names.append("rain") # 数据会追加到尾部 >>> names.append("eva") >>> >>> names ['alex', 'jack', 'rain', 'eva']
插入
>>> names.insert(2,"黑姑娘") # 可插入任何位置 >>> names ['alex', 'jack', '黑姑娘', 'rain', 'eva'] # 当要在最后个位置增加时,用append,因为insert会把原来位置的元素往后挤
合并
>>> n2 = ["狗蛋","绿毛"] >>> names ['alex', 'jack', '黑姑娘', 'rain', 'eva'] >>> names.extend(n2) # 可以把另一外列表的值合并进来,()里面的拼接在最后 >>> names ['alex', 'jack', '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛']
列表嵌套
>>> names.insert(2,[1,2,3]) # 把[1,2,3]插入到2位置 >>> names ['alex', 'jack', [1, 2, 3], '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛'] >>> names[2][1] # 访问到names的2位置,再在里面访问1 2
删除操作
del删
>>> names ['alex', 'jack', [1, 2, 3], '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛', '鸡头'] >>> del names[2] # 找到下标2的位置,删除它 >>> names ['alex', 'jack', '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛', '鸡头']
pop删
>>> names ['alex', 'jack', '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛', '鸡头'] >>> names.pop() # 默认删除最后一个元素并返回被删除的值 '鸡头' >>> names ['alex', 'jack', '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛'] >>> help(names.pop) >>> names.pop(1) # 删除指定元素 'jack' # 删除之后返回删除的值
清空
>>> n2 ['狗蛋', '绿毛', '鸡头'] >>> n2.clear() # 清空该列表里面的元素 >>> n2 []
修改操作
>>> names ['alex', '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛'] >>> names[0] = "金角大王" # 修改0上面的元素 >>> names[-1] = "银角大王" # 修改-1上面的元素 >>> names ['金角大王', '黑姑娘', 'rain', 'eva', '狗蛋', '银角大王']
查操作
>>> names ['金角大王', '黑姑娘', 'rain', 'eva', '狗蛋', '银角大王', 'eva'] >>> >>> names.index("eva") # 返回从左开始匹配到的第一个eva的索引 3 >>> names.count("eva") # 返回eva的个数 2
切片
>>> names ['金角大王', '黑姑娘', 'rain', 'eva', '狗蛋', '银角大王', 'eva'] >>> names[1:4] # 不包含下标4的元素 ['黑姑娘', 'rain', 'eva'] >>> names[-5:-1] # 倒着切 ['rain', 'eva', '狗蛋', '银角大王'] >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a[0:7:2] # 设置步长为2 [0, 2, 4, 6]
列表反转
>>> a[::-1] # 通过把步长设置成负值,可达到列表返转的效果 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> a[::-2] [9, 7, 5, 3, 1] # 同样,在字符串里面也适用 >>> asd = 'asdfghjkl' >>> asd[ : :-1] 'lkjhgfdsa'
排序
>>> a = [83,4,2,4,6,19,33,21] >>> a.sort() # 排序 >>> a [2, 4, 4, 6, 19, 21, 33, 83]
>>> names=['金角大王', 'rain', '@', '黑姑娘', '狗蛋', "4","#",'银角大王', 'eva'] >>> names.sort() # 字符根据ASCII排序 >>> names ['#', '4', '@', 'eva', 'rain', '狗蛋', '金角大王', '银角大王', '黑姑娘']
反转
>>> names ['#', '4', '@', 'eva', 'rain', '狗蛋', '金角大王', '银角大王', '黑姑娘'] >>> names.reverse() # 反转 >>> names ['黑姑娘', '银角大王', '金角大王', '狗蛋', 'rain', 'eva', '@', '4', '#']
循环列表
>>> for i in names: ... print(i) ... 黑姑娘 银角大王 金角大王 狗蛋 rain eva @ 4 #