700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 金丹期前期:1.4 python语言-python的程序的核心数据类型:字符串 列表 元组 字典

金丹期前期:1.4 python语言-python的程序的核心数据类型:字符串 列表 元组 字典

时间:2020-02-03 09:04:35

相关推荐

金丹期前期:1.4 python语言-python的程序的核心数据类型:字符串 列表 元组 字典

一、字符串

1、字符串的表示方式

双引号或者单引号中的数据,就是字符串,如下所示:

a = "hello "b = 'hello '

2、字符串的输出

name = "Linbo" #""双引号position = '工程师' #''单引号address = "杭州市余杭区"print('--------------------------------------------------')print("姓名:%s"%name)print("职位:%s"%position)print("公司地址:%s"%address)print('--------------------------------------------------')

3、字符串的输入

userName = input('请输入用户名:')print("用户名为:%s"%userName)password = input('请输入密码:')print("密码为:%s"%password)

input获取的数据,都以字符串的方式进行保存,即使输入的是数字,那么也是以字符串方式保存!!

4、字符串的常用操作(可认为是string对象的方法,但不改变原有字符串对象)

find:检测 str 是否包含在 mystr中,如果是返回str开始的索引值,否则返回-1

#!/usr/bin/python3#coding=utf-8mystr = "Linbo, you have to play the game!!"str1 = "Linbo"str2 = "game"str3 = "them"l1= mystr.find(str1)l2= mystr.find(str2)l3= mystr.find(str3)print("Str1 local:%d"%l1)print("Str2 local:%d"%l2)print("Str3 local:%d"%l3)

输出结果:

Str1 local:0Str2 local:28Str3 local:-1

关键词:初始位置为0,中间的字符和空格都是算位置的!!

index:跟find()方法一样,只不过如果str不在 mystr中会报一个异常.

#!/usr/bin/python3#coding=utf-8mystr = "Linbo, you have to play the game!!"str1 = "Linbo"str2 = "game"str3 = "them"l1= mystr.find(str1)print("Str1 local:%d"%l1)l2= mystr.index(str2)print("Str2 local:%d"%l2)l3= mystr.index(str3)print("Str3 local:%d"%l3)

输出结果:

Str1 local:0Str2 local:28Traceback (most recent call last):File "./1string.py", line 15, in <module>l3= mystr.index(str3)ValueError: substring not found

关键词:index需要用在异常处理处使用!!

count:返回 str在start和end之间 在 mystr里面出现的次数

#!/usr/bin/python3#coding=utf-8mystr = "Linbo, you have to play the game!!"str1 = "Linbo"str2 = "game"str3 = "a"l1= mystr.find(str1)print("Str1 local:%d"%l1)l2= mystr.index(str2)print("Str2 local:%d"%l2)l3= mystr.count(str3)print("Str3 count:%d"%l3)

执行结果:

Str1 local:0Str2 local:28Str3 count:3

replace(str1,str2,mystr.count(str)):把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.

#!/usr/bin/python3#coding=utf-8mystr = "Linbo, you have to play the game!!"str1 = "Linbo"str2 = "game"str3 = "a"str4 = "life"str5 = mystr.replace(str2,str4)print("mystr:%s"%mystr)print("ret_str:%s"%str5)str7 = mystr.replace(str3,'c',2)print("mystr:%s"%mystr)print("ret_str:%s"%str7)

执行结果:

mystr:Linbo, you have to play the game!!ret_str:Linbo, you have to play the life!!mystr:Linbo, you have to play the game!!ret_str:Linbo, you hcve to plcy the game!!

关键词:mystr字符串不会改变,运算结果是变换后的字符串

split:以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串

list1 = mystr.split(" ")print(list1)list2 = mystr.split(" ",2)print(list2)

执行结果:

['Linbo,', 'you', 'have', 'to', 'play', 'the', 'game!!']['Linbo,', 'you', 'have to play the game!!']

关键词:分割之后的元素组成列表

capitalize:把字符串的第一个字符大写

title:把字符串的每个单词首字母大写

startswith:检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False

endswith:检查字符串是否以obj结束,如果是返回True,否则返回 False.

lower:转换 mystr 中所有大写字符为小写

upper:转换 mystr 中的小写字母为大写

print("%d"%mystr.startswith("Linbo"))print("%d"%mystr.startswith("linbo"))print("%d"%mystr.endswith("life!!"))print("%d"%mystr.endswith("game!!"))print("%s"%mystr.lower())print("%s"%mystr.title())print("%s"%mystr.lower())print("%s"%mystr.upper())print("%s"%mystr.lower())print("%s"%mystr.capitalize())

执行结果:

1001linbo, you have to play the game!!Linbo, You Have To Play The Game!!linbo, you have to play the game!!LINBO, YOU HAVE TO PLAY THE GAME!!linbo, you have to play the game!!Linbo, you have to play the game!!

ljust:返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串

rjust:返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串

center:返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

lstrip:删除 mystr 左边的空白字符

rstrip:删除 mystr 字符串末尾的空白字符

strip:删除mystr字符串两端的空白字符

#!/usr/bin/python3#coding=utf-8mystr = "Linbo, you have to play the game!!"str1 = " Linbo"str2 = "game "str3 = "a"str4 = "life"print("=================================================")print("%s"% mystr.ljust(50))print("%s"% mystr.rjust(50))print("%s"% mystr.center(50))print("=================================================")print(str1.lstrip())print(str2.rstrip())print(str3.strip())

执行结果:

=================================================Linbo, you have to play the game!!Linbo, you have to play the game!!Linbo, you have to play the game!! =================================================Linbogamea

rfind:类似于 find()函数,不过是从右边开始查找

rindex:类似于 index(),不过是从右边开始.

partition:把mystr以str分割成三部分,str前,str和str后

#!/usr/bin/python3#coding=utf-8mystr = "Linbo, you have to play the game!!"str1 = " Linbo"str2 = "game "str3 = "a"str4 = "have to"print(mystr.partition(str4))

执行结果:

('Linbo, you ', 'have to', ' play the game!!')

关键词:返回结果是一个元组.

rpartition:类似于 partition()函数,不过是从右边开始.

splitlines:按照行分隔,返回一个包含各行作为元素的列表

#!/usr/bin/python3#coding=utf-8mystr = "Linbo,\n you have to\n play the game!!"str1 = " Linbo"str2 = "game "str3 = "a"str4 = "have to"print(mystr.splitlines())

执行结果如下:

['Linbo,', ' you have to', ' play the game!!']

关键词:执行结果为列表

isalpha:如果 mystr 所有字符都是字母 则返回 True,否则返回 False

isdigit:如果 mystr 只包含数字则返回 True 否则返回 False.

isalnum:如果 mystr 所有字符都是字母或数字则返回 True,否则返回 False

isspace:如果 mystr 中只包含空格,则返回 True,否则返回 False.

#!/usr/bin/python3#coding=utf-8mystr = "Linbo,you have to play the game!!"str1 = "12344"str2 = "game123445 "str3 = "a1 "str4 = ""print(mystr.isalpha())print(str1.isdigit())print(str2.isalnum())print(str3.isalpha())print(str4.isspace())

执行结果如下:

FalseTrueFalseFalseTrue

join:list1中每个字符间隔处加一个"_",构造成一个新的字符串。

#!/usr/bin/python3#coding=utf-8list1 = ["Linbo","you","have to","play the game!!"]print("-".join(list1))print(" ".join(list1))

运行结果:

Linbo-you-have to-play the game!!Linbo you have to play the game!!

二、列表

1、列表的格式及其打印方式

#!/usr/bin/python3#coding=utf-8list = [1,True,"Linbo",3.14]print(list)print(list[0])print(list[1])print(list[2])print(list[3])

运行结果:

[1, True, 'Linbo', 3.14]1TrueLinbo3.14

关键词:列表内的元素可以是不同类型的,其数值打印方式可以整体打印也可以分开打印。

2、列表的遍历操作

为了更有效率的输出列表的每个数据,可以使用循环来完成

#!/usr/bin/python3#coding=utf-8list1 = [1,True,"Linbo",3.14]print(list1)print("===============")print(list1[0])print(list1[1])print(list1[2])print(list1[3])print("===============")for elem in list1:print(elem)print("===============")length = len(list1)i = 0while i<length:print(list1[i])i+=1

运行结果:

[1, True, 'Linbo', 3.14]===============1TrueLinbo3.14===============1TrueLinbo3.14===============1TrueLinbo3.14

关键词:python中没有++操作符。while中要先定义变量,获取长度才能操作列表。

3、列表的常用操作(列表对象的方法,会改变列表对象本身)

添加元素

末尾添加一个元素:list1.append(elem)末尾添加一组元素: list1.extend(list2)指定位置添加元素: list1.insert(index,elem)

#!/usr/bin/python3#coding=utf-8list1 = [1,True,"Linbo",3.14]list2 = ["Linbo","have to","play game!!"]print(list1)print("=================")list1.append(10)print(list1)print("=================")list1.append(list2)print(list1)print("=================")list1.extend(list2)print(list1)print("=================")

运行结果:

[1, True, 'Linbo', 3.14]=================[1, True, 'Linbo', 3.14, 10]=================[1, True, 'Linbo', 3.14, 10, ['Linbo', 'have to', 'play game!!']]=================[1, True, 'Linbo', 3.14, 10, ['Linbo', 'have to', 'play game!!'], 'Linbo', 'have to', 'play game!!']=================[1, True, 1111, 'Linbo', 3.14, 10, ['Linbo', 'have to', 'play game!!'], 'Linbo', 'have to', 'play game!!']

关键词:以下是错误的示例

list1 = ["Linbo","have to","play game!!"]

list1[3] = "11111" #这种添加方式是错误的!!!

删除元素

del:根据下标进行删除pop:删除最后一个元素remove:根据元素的值进行删除

#!/usr/bin/python3#coding=utf-8list1 = ["Linbo","have to","play game!!"]print(list1)print("=================")list1.pop()print(list1)print("=================")list1.remove("Linbo")print(list1)print("=================")del list1[0]print(list1)

结果输出:

​['Linbo', 'have to', 'play game!!']=================['Linbo', 'have to']=================['have to']=================[]​

关键词:del不是方法,是个函数

修改元素

要通过下标来确定要修改的是哪个元素,然后才能进行修改

list1[0] = "play again"

查找元素

in(存在),如果存在那么结果为true,否则为falsenot in(不存在),如果不存在那么结果为true,否则falseindex与字符串中的用法一样count与字符串中的用法一样

#!/usr/bin/python3#coding=utf-8list1 = ["Linbo","have to","play game!!"]a= "Linbo"if a in list1:print("list1 inlcude a")print(list1.index(a,0,3))print(list1.count("have to"))

运行结果:

list1 inlcude a01

排序元素

sort:将list按特定顺序重新排列,默认为由小到大,参数reverse=True可改为倒序,由大到小。reverse:是将list逆置.

#!/usr/bin/python3#coding=utf-8list1 = ["Linbo","have to","play game!!"]print(list1)list1.sort()print(list1)list1.sort(reverse=True)print(list1)list1.reverse()print(list1)

运行结果:

['Linbo', 'have to', 'play game!!']['Linbo', 'have to', 'play game!!']['play game!!', 'have to', 'Linbo']['Linbo', 'have to', 'play game!!']

4.列表可以嵌套使用

#encoding=utf-8import random# 定义一个列表用来保存3个办公室offices = [[],[],[]]# 定义一个列表用来存储8位老师的名字names = ['A','B','C','D','E','F','G','H']i = 0for name in names:index = random.randint(0,2) offices[index].append(name)i = 1for tempNames in offices:print('办公室%d的人数为:%d'%(i,len(tempNames)))i+=1for name in tempNames:print("%s"%name,end='')print("\n")print("-"*20)

三、元组

Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号。

所以元组只能通过索引获取数据,不能修改数据,任何方式的修改元组的数值都会出错

元组的内置函数:

count:与字符串和列表中的用法相同index:与字符串和列表中的用法相同

四、字典

1、字典的表示形式:{ }

info = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区'}

字典和列表一样,也能够存储多个数据列表中找某个元素时,是根据下标进行的字典中找某个元素时,是根据'名字'(就是冒号:前面的那个值,例如上面代码中的'name'、'id'、'sex')字典的每个元素由2部分组成,键:值。

2、根据key访问value

#! /usr/bin/python3#encoding=utf-8dict1 = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区',1:"hello"}print(dict1)print(dict1['name'])print(dict1['id'])print(dict1[1])print(dict1['age'])

运行结果:

{1: 'hello', 'id': 100, 'sex': 'M', 'address': '杭州市余杭区', 'name': 'Linbo'}Linbo100helloTraceback (most recent call last):File "./4dict.py", line 10, in <module>print(dict1['age'])KeyError: 'age'

关键词:访问不存在的索引值会报错,key的数据类型可以是多样的

3、字典常用的操作

获取元素:get(key)是另一种获取值的方法修改元素:只要通过key找到,即可修改

添加元素:如果在使用变量名['键'] = 数据时,这个“键”在字典中,不存在,那么就会新增这个元素

删除元素:

del:del dict1['name'] 删除一个,del dict1 删除字典,删除不存在的也会报错clear():清空整个字典

#! /usr/bin/python3#encoding=utf-8dict1 = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区'}print(dict1)print(dict1.get('name'))print(dict1.get('age'))dict1['id'] = 99print(dict1)dict1['age'] = 24print(dict1)del dict1['age']print(dict1)dict1.clear()print(dict1)

执行结果:

{'address': '杭州市余杭区', 'name': 'Linbo', 'sex': 'M', 'id': 100}LinboNone{'address': '杭州市余杭区', 'name': 'Linbo', 'sex': 'M', 'id': 99}{'address': '杭州市余杭区', 'name': 'Linbo', 'age': 24, 'sex': 'M', 'id': 99}{'address': '杭州市余杭区', 'name': 'Linbo', 'sex': 'M', 'id': 99}{}

len:测量字典中,键值对的个数

keys:返回一个包含字典所有KEY的列表

values:返回一个包含字典所有value的列表

items:返回一个包含所有(键,值)元祖的列表

has_key:如果key在字典中,返回True,否则返回False

#! /usr/bin/python3#encoding=utf-8dict1 = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区'}print(dict1)print(len(dict1))l1=dict1.keys()print(l1)print(dict1.values())print(dict1.items())print(dict1.has_key('name'))

运行结果:

{'name': 'Linbo', 'id': 100, 'sex': 'M', 'address': '杭州市余杭区'}4dict_keys(['name', 'id', 'sex', 'address'])dict_values(['Linbo', 100, 'M', '杭州市余杭区'])dict_items([('name', 'Linbo'), ('id', 100), ('sex', 'M'), ('address', '杭州市余杭区')])Traceback (most recent call last):File "./4dict.py", line 13, in <module>print(dict1.has_key('name'))AttributeError: 'dict' object has no attribute 'has_key'

关键词:没有has_key???,

遍历字典的方法:

#! /usr/bin/python3#encoding=utf-8dict1 = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区'}print(dict1)print('=============')for key in dict1.keys():print(key)print('=============')for value in dict1.values():print(value)print('=============')for item in dict1.items():print(item)

运行结果:

{'address': '杭州市余杭区', 'id': 100, 'name': 'Linbo', 'sex': 'M'}=============addressidnamesex=============杭州市余杭区100LinboM=============('address', '杭州市余杭区')('id', 100)('name', 'Linbo')('sex', 'M')

五、下标和切片(以字符串为例)

(1)列表与元组支持下标索引,字符串实际上就是字符的数组,所以也支持下标索引

name = 'Linbo' :

(2)切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作

切片的语法:[起始:结束:步长]

注意:选取的区间属于左闭右开型意型[ )。 即从"起始"位开始,到"结束"位的前一位结束(不包含结束位本身)。如果结束位为空,那么表明是到结尾.

如果步长为负值,那么是往前数.

如果结束为负值,-1表示是最后一个字符,但是记得左闭右开的原则

name = "Linbo"

切片 执行结果(右侧可以超出范围)

六、另一种通用的遍历方法(迭代器)

enumerate:遍历时候可以加上索引

#! /usr/bin/python3#encoding=utf-8dict1 = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区'}list1 = ['a', 'b', 'c', 'd']for i, chr in enumerate(list1):print(i, chr)print('======================')t1 = (1,2,3,4)for i, chr in enumerate(t1):print(i, chr)print('======================')for i, chr in enumerate(dict1):print(i, chr)

运行结果:

0 a1 b2 c3 d======================0 11 22 33 4======================0 id1 address2 sex3 name

关键词:注意字典无顺序可言,而且只是key

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。