(一)数字
Python3中的数字类型分为3种,分别是整型,浮点型以及复数。
Python2种的数字类型分为4种,分别是整型,长整型,浮点型以及复数。
其中长整型时Python2为应对位数较大的而设置的类型,整数最后是一个大写或小写的L。
主要函数:
int() 将字符串等类型转换成数字类型
(二)字符串
Python中的字符串使用 ' 或 “ 来创建。
主要函数:
1、replace() 使用新的字符串替换原来的字符串
#!/sur/bin/python3 str = "www.w3cschool.cc" print("菜鸟教程旧地址:",str) print("菜鸟教程新地址:",str.replace("w3cschool.cc","runoob.com")) str = "this is string example....wow!!!" print(str.replace("is","was",1)
2、find() 检查字符串中是否包含子字符串,如果有则返回该子字符串的索引值,没有则返回-1
#!/sur/bin/python3 str1 = "Runoob example....wow!!!" str2 = "exam"; print(str1.find(str2)) print(str.find(str2,5))
3、join() 用于将序列中的元素以指定的字符连接生成新的字符串
#!/usr/bin/python3 s1 = "-" s2 = "" seq = ("h","e","l","l","o") print(s1.join( seq )) print(s2.join( seq ))
4、startswith() 检查字符串是否以制定字符串开头,是则返回true 否则返回false
#!/sur/bin/python3 str = "this is string example....wow!!!" print(str.startswith( 'this' )) print(str.startswith( 'sting',8 )) print(str.startswith( 'this',2,4 ))
5、split() 通过指定字符对字符串进行切片
#!/syr/bin/python3 str = "this is string example...wow!!!" print(str.split( )) print(str.split('i',1)) print(str.split('w'))
6、format() 格式化字符串
#!/sur/bin/python site = {"name": "菜鸟教程", "url": "www.runoob.com"} print("网站名:{name}, 地址 {url}".format(**site))
7、upper以及lower
将字符串中的大小写互相转换
(三)列表
序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
格式如下:
#!/usr/bin/python3 list = ['Google', 'Runoob', 1997, 2000]
主要函数:
1、append() 在列表尾部添加新的对象
#!/sur/bin/python3 list1 = ['Google','Runoob','Taobao'] list1.append('Baidu') print(list1)
2、extend() 用于在列表末尾一次性追加另一个序列中的多个值。
#!/usr/bin/python3 list1 = ['Google', 'Runoob', 'Taobao'] list2=list(range(5)) # 创建 0-4 的列表 list1.extend(list2) # 扩展列表 print ("扩展后的列表:", list1)
3、insert() 用于将指定对象插入列表的指定位置。
#!/usr/bin/python3 list1 = ['Google', 'Runoob', 'Taobao'] list1.insert(1, 'Baidu') print ('列表插入元素后为 : ', list1)
(四)元组
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
格式如下:
#!/usr/bin/python3 tup1 = ('Google', 'Runoob', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7 )
(五)字典
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})。
格式如下:
#!/usr/bin/python3 dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} print ("dict['Name']: ", dict['Name']) print ("dict['Age']: ", dict['Age'])
1、get() 返回指定键的值,如果值不在字典中返回默认值。
#!/usr/bin/python3 dict = {'Name': 'Runoob', 'Age': 27} print(dict.get(''Age))
2、update() 把字典参数 dict2 的 key/value(键/值) 对更新到字典 dict 里。
#!/usr/bin/python3 dict = {'Name': 'Runoob', 'Age': 7} dict2 = {'Sex': 'female' } dict.update(dict2) print ("更新字典 dict : ", dict)
3、items() 以列表返回可遍历的(键, 值) 元组数组。
#!/usr/bin/python3 dict = {'Name': 'Runoob', 'Age': 7} print ("Value : %s" % dict.items())
(六) 集合
Python的集合类型是一个无序的不重复序列。
#!/sur/bin/python3 hobby = {'play','study','see movie'} print(hobby)