最全python结构操作----附代码

"""

有关字符串的操作

"""
str1="我和我的祖国,一刻也不能分割"
str2="I Love China,I Will stay with my country"

#find函数:在字符串中查找要查找的字符,如果该字符存在,那么返回该字符的索引,如果不存在,那么返回-1
#具体使用方法:str1.find(s,0,len(str1))
print(str1.find("国",0,len(str1)))  #运行结果:5
print(str1.find("齐",0,len(str1)))  #运行结果:-1

#index方法:在字符串中查找要查找的字符,如果该字符存在,就返回该字符的索引,如果不存在,则报错
#具体使用方法:str1.index(s,0,len(str1))
print(str1.index("和",0,len(str1)))  #运行结果:1
try:
    print(str1.index("齐",0,len(str1)))
except Exception as result:
    print("该字符串中没有这个字符,您查找出错啦")  #运行结果:该字符串中没有这个字符,您查找出错啦
    print(f"该错误内容是:{result}")  #运行结果:该错误内容是:substring not found

#count方法:返回字符串str1中字符s的个数
#具体用法:str1.count(s,0,len(str1))
print(str1.count("我",0,len(str1)))  #运行结果:2

#replace方法:将str1中的s1替换成s2,并返回新的字符串,如果count指定,则替换次数不能超过count次
#具体用法:str1.replace(s1,s2,str1.count(s1))
str3=(str1.replace("我","你",str1.count("我")))#并没有改变原来的字符串,而是生成了一个新的字符串
print(str3) #运行结果:你和你的祖国,一刻也不能分割
print(str1) #运行结果:我和我的祖国,一刻也不能分割

#split方法:用s1作为分隔符分割字符串str1(s1必须存在于str1,否则是没有用的),如果num参数指定,则之分割前num个子串
#使用方法:str1.split(s1,num)
print(str1.split("我",2)) #运行结果:['', '和', '的祖国,一刻也不能分割']

#title方法:让字符串中每个单词的首字母大写
#使用方法:str2.title()
print(str2.title())  #运行结果:I Love China,I Will Stay With My Country

#startswith方法:查看字符串s1是不是字符串str1的开头,如果是,返回true,否则返回false
#具体用法:str1.startswith(s1)
print(str2.startswith("I"))  #运行结果:True

#endswith方法:查看字符串s1是否是字符串str1的末尾,如果是,返回true,否则返回false
#具体用法:str1.endswith(s1)
print(str2.endswith("try"))  #运行结果:True

#lower方法:将字符串str1中的所有字母转化为小写字母
#具体用法:str1.lower()
str4=str2.lower()  #是生成了一个新的字符串,没有改变原来的字符串
print(str4)  #运行结果:i love china,i will stay with my country
print(str2)  #运行结果:I Love China,I Will stay with my country

#upper方法:将字符串str1中的所有字符转换为大写
#具体用法:str1.upper()
str5=str2.upper()  #生成了一个新的字符串,没有改变原来的字符串
print(str5)  #运行结果:I LOVE CHINA,I WILL STAY WITH MY COUNTRY
print(str2)  #运行结果:I Love China,I Will stay with my country

#ljust方法:让字符串str1左对齐,并用空格填充至长度为weight
#具体用法:str1.ljust(weight)
str6=str1.ljust(30)  #生成了一个新的字符串,没有改变原来的字符串
print(str6)  #运行结果:我和我的祖国,一刻也不能分割
print(str1)  #运行结果:我和我的祖国,一刻也不能分割

#rjust方法:让字符串str1右对齐,并用空格填充至长度为weight
#具体用法:str1.rjust(weight)
str7=str1.rjust(30)  #生成了一个新的字符串,没有改变原来的字符串
print(str7)  #运行结果:                我和我的祖国,一刻也不能分割
print(str1)  #运行结果:我和我的祖国,一刻也不能分割

#center方法:让字符串str1居中,并用空格填充至长度为weight
#具体用法:str1.center(weight)
str8=str1.center(30)  #生成了一个新的字符串,没有改变原来的字符串
print(str8)  #运行结果:        我和我的祖国,一刻也不能分割
print(str1)  #运行结果:我和我的祖国,一刻也不能分割

#lstrip方法:删除字符串str1左边的空白部分
#具体用法:str1.lstrip()
str9=str7.lstrip()  #生成了一个新的字符串,没有改变原来的字符串
print(str9)  #运行结果:我和我的祖国,一刻也不能分割
print(str7)  #运行结果:                我和我的祖国,一刻也不能分割

#rstrip方法:删除字符串str1右边的空白部分
#具体用法:str1.rstrip()
str10=str6.rstrip()  #生成了一个新的字符串,没有改变原来的字符串
print(str10)  #运行结果:我和我的祖国,一刻也不能分割
print(str6)  #运行结果:我和我的祖国,一刻也不能分割

#strip方法:删除字符串str1两边的空白部分
#具体用法:str1.strip()
str11=str8.strip()  #生成了一个新的字符串,没有改变原来的字符串
print(str11)  #运行结果:我和我的祖国,一刻也不能分割
print(str8)  #运行结果:        我和我的祖国,一刻也不能分割

#rfind方法:类似于find方法,只不过是从字符串str1右边开始查找
#具体用法:str1.rfind(s1,0,len(str1))
print(str1.rfind("不",0,len(str1)))  #运行结果:10

#rindex方法:类似于index方法,只不过是从字符串str1右边开始查找
#具体用法:str1.rindex(s1,0,len(str1))
print(str1.rindex("国",0,len(str1)))  #运行结果:5

#partition方法:将字符串str1从字符串(字符)s1分割为三部分,s1之前、s1、s1之后,并将三个字符串放进一个元组中
#具体用法:str1.partition(s1)
str12=str1.partition("国,")  #生成了一个元组,没有改变原来的字符串
print(str12)  #运行结果:('我和我的祖', '国,', '一刻也不能分割')
print(type(str12))  #运行结果:<class 'tuple'>
print(str1)  #运行结果:我和我的祖国,一刻也不能分割

#rpartition方法:和partition类似,只不过是从右边开始
#具体用法:str1.rpartition(s1)
str13=str1.rpartition("我")  #生成了一个元组,并没有改变原来的字符串
print(str13)  #运行结果:('我和', '我', '的祖国,一刻也不能分割')

#isalpha方法:判断字符串str1是否均为字母,如果是,返回True,否则返回false
#具体用法:str1.isalpha()
print(str1.isalpha())  #运行结果:False
print(str2.isalpha())  #运行结果:False  因为其中有逗号” , “

#isalnum方法:判断字符串str1中是否都为字母或者数字,如果是,返回true,否则返回false
#具体用法:str1.isalnum()
print(str1.isalnum())  #运行结果:False
print(str2.isalnum())  #运行结果:False

#isdigit方法:判断字符串str1中是否都是数字,如果是,返回True,否则返回False
#具体用法:str1.isdigit()
print(str1.isdigit())  #运行结果:False
s="123456"
print(s.isdigit())  #运行结果:True

#isspace方法:判断字符串str1是否均由空格组成,如果是,返回True,否则返回False
#具体用法:str1.isspace()
print(str1.isspace())  #运行结果:False
print("    ".isspace())  #运行结果:True

#join方法:在str1中每个字符后面插入字符s
#具体用法:s.join(str1)
print("_".join(str1))  #运行结果:我_和_我_的_祖_国_,_一_刻_也_不_能_分_割

"""

有关列表的操作

"""
lst1=[1,2,3,4,5,6,7]
lst2=["我","和","我","的","祖","一","刻","也","不","能","分","割"]
lst3=[]

#append方法:在列表lst1中添加元素s1
#具体用法:lst1.append(s1)
lst1.append(8)  #改变了原列表
print(lst1)  #运行结果:[1, 2, 3, 4, 5, 6, 7, 8]

#extend方法:将另一个集合lst2中的元素逐一添加至lst1中
#具体用法:lst1.extend(lst2)
lst1.extend(lst2)  #改变了原来的列表
print(lst1)  #运行结果:[1, 2, 3, 4, 5, 6, 7, 8, '我', '和', '我', '的', '祖', '一', '刻', '也', '不', '能', '分', '割']

#insert方法:在列表lst1指定位置index的前面插入元素s1
#具体用法:lst1.insert(index,s1)
lst1.insert(2,"我喜欢齐晨")  #改变了原来的列表
print(lst1)  #运行结果:[1, 2, '我喜欢齐晨', 3, 4, 5, 6, 7, 8, '我', '和', '我', '的', '祖', '一', '刻', '也', '不', '能', '分', '割']

#del方法:按列表lst1中元素s1的下标index来删除元素s1
#具体用法:del lst1[index]
del lst1[2]  #改变了原来的列表
print(lst1)  #运行结果:[1, 2, 3, 4, 5, 6, 7, 8, '我', '和', '我', '的', '祖', '一', '刻', '也', '不', '能', '分', '割']

#pop方法:删除列表lst1的最后一个元素
#具体用法:lst1.pop()
lst1.pop()  #改变了原来的列表
print(lst1)  #运行结果:[1, 2, 3, 4, 5, 6, 7, 8, '我', '和', '我', '的', '祖', '一', '刻', '也', '不', '能', '分']

#remove方法:根据元素的值来删除列表lst1中的元素s1
#具体用法:lst1.remove(s1)
lst1.remove("我")  #改变了原来的列表
print(lst1)  #运行结果:[1, 2, 3, 4, 5, 6, 7, 8, '和', '我', '的', '祖', '一', '刻', '也', '不', '能', '分']

#sort方法:将列表lst1进行排序,默认为从小到大,如果对参数改为reverse=True,则会从大到小进行排列
#具体用法:lst1.sort()    逆序:lst1.sort(reverse=True)
lst3=[1,2,4,7,3,0]
lst3.sort()  #改变了原来的列表
print(lst3)  #运行结果:[0, 1, 2, 3, 4, 7]
lst3.sort(reverse=True)   #改变了原来的列表
print(lst3)  #运行结果:[7, 4, 3, 2, 1, 0]

#reverse方法:对列表lst1进行排序,从小到达
lst3.reverse()
print(lst3)


"""

字典的相关操作

"""
dic1={"张一飞":21,"齐晨":20}
dic2={}

#改值方法:用key方法找到想要找到的键,以此来修改此键的值为value1
#具体用法:dic1[key]=value1
dic1["张一飞"]=20
print(dic1["张一飞"])  #运行结果:20

#添加元素:dic1[想添加的键]=键的值
dic1["程雨"]=20
print(dic1["程雨"])  #运行结果:20

#del方法:删除字典中的某一项
#具体用法:del dic1[想删除的键]
del dic1["程雨"]
try:
    print(dic1["程雨"])
except Exception as result:
    print("出错了!")
    print(f"本次错误为:{result}")
    """运行结果:出错了!
    本次错误为:'程雨'"""

#clear方法:清空整个字典
#具体用法:dic1.clear()
dic1.clear()
print(dic1)  #运行结果:{}
print(len(dic1))  #运行结果:0

#keys方法:以列表形式返回字典dic1中的所有键,但是返回的不是真正的列表,如果要以列表返回,则需要用list()方法进行转换
#具体用法:dic1.keys()
dic1={"张一飞":21,"齐晨":20}
ls=dic1.keys()
print(type(ls))  #运行结果:<class 'dict_keys'>
print(ls)  #运行结果:dict_keys(['张一飞', '齐晨'])
ls=list(ls)
print(type(ls))  #运行结果:<class 'list'>
print(ls)  #运行结果:['张一飞', '齐晨']

#values方法:以列表形式返回字典dic1中的值,但是返回的不是真正的列表,如果要以列表返回,需要用list()方法进行转换
#具体用法:dic1.values()
ls2=dic1.values()
print(type(ls2))  #运行结果:<class 'dict_values'>
print(ls2)  #运行结果:dict_values([21, 20])
ls2=list(ls2)
print(type(ls2))  #运行结果:<class 'list'>
print((ls2))  #运行结果:[21, 20]

#items方法:返回一个键值对元组的列表,但是不是真正的列表,如需要以列表形式返回,需要用list()方法进行转换
#具体用法:dic1.items()
ls3=dic1.items()
print(type(ls3))  #运行结果:<class 'dict_items'>
print(ls3)  #运行结果:dict_items([('张一飞', 21), ('齐晨', 20)])
ls3=list(ls3)
print(type(ls3))  #运行结果:<class 'list'>
print(ls3)  #运行结果:[('张一飞', 21), ('齐晨', 20)]

#has_key方法:判断key键是否在dic1中,如果在,返回True,否则返回False
#具体用法:dic1.has_key(key)
try:
    print(dic1.has_key("齐晨"))
except Exception as resule:
    print("程序出错了")
    print(f"错误原因是:{resule}")

"""运行结果为:错误原因是:'dict' object has no attribute 'has_key',查阅资料显示has_key方法在python3删除了,所以如果要判断key
是否在dic1中,只能好用if key in dic1.keys()了"""

if "齐晨" in dic1.keys():
    print("齐晨在dic1中")

"""
公共方法

"""

#python3已经取消cmp方法,cmp方法在python2中的作用是比较两个值的大小,用法是cmp(s1,s2)

"""
现存公共方法有:min、max、len、del、sum,其中,sum是python3中新添加的方法
"""
ls=[1,2,3,4,5]
print(sum(ls))

"""

文件的相关操作

"""
#open方法:打开文件,其中打开形式有:r:只读,w:写,a:读写,r+:读写,w+:读写。a+:读写。rb:以二进制只读方式打开。wb:以二进制写的方式打开.ab:以二进制读写形式打开
f=open("文件名","打开形式")
#close方法:关闭文件
f.close()

#write方法:写入数据到文件中,必须以能写的方式打开文件才可以用
f=open("文件名","w、a、w+、r+、a+等")
f.write("要写的内容")
f.close()

#read(num)方法:从文件中读数据,num表示字节,即读入多少个字节,如果不赋值,默认为全文
f=open("文件名","r")
print(f.read())
f.close()

#readline()方法:读取下一行,也就是没调用一次就读该文件中上次调用的行的下一行
f=open("文件名","r")
print(f.readline())
f.close()

#readlines方法:从文件中一行一行的读入数据,并将每一行的元素存入一个列表中
f=open("文件名","r")
print(f.readlines())
f.close()

#tell方法:在读写文件的时候,如果想知道当前的位置,可以使用tell方法来获取当前位置
f=open("文件名","打开方式")
f.readline()
f.tell()
f.close()

#文件重命名,需要先引入python自带的os模块,即import os,然后进行操作:os.rename("需要修改的文件名,"想要改成的文件名")
import os
os.rename("想要修改的文件名","想要改成的文件名")

#删除文件,在os模块下的remove方法可以删除文件
import os
os.remove("想要删除的文件名")

#创建文件夹,使用os模块下的mkdir方法进行创建
import os
os.mkdir("想要创建的文件夹名")

#获取当前目录,使用os目录下的getcwd方法进行获取
import os
os.getcwd()

#改变默认目录,使用os模块下的chdir方法进行改变
import os
os.chdir("。。。。。/")

#删除文件夹,使用os模块下的rmdir方法进行删除
import os
os.rmdir("想要删除的文件夹名")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值