Python语言基础-03

来源:互联网 发布:《申报》数据库 编辑:程序博客网 时间:2024/06/15 10:04

 主要内容:

  • 1.for循环使用
  • 2.切片的应用
  • 3.字符串常见操作
  • 4.列表使用
  • 5.元组
  • 6.字典

1.字符串:
1)通俗意义上将就是单引号或双引号内的所有内容;
2)字符串不一定要用变量存储
2.for循环与while循环使用
1)while循环
name = 'abcde'
i = 0
#len函数可以获取字符串长度
while i<len(name):
    #Python中,数组的下标索引从0开始
    print(name[i],end="  ")
    i+=1
'''结果:
a  b  c  d  e 
'''
2)for循环
name = 'abcde'
#每次for循环,temp取name中的一个值,默认步长为1
for temp in name:
    print(temp,end=" ")
'''结果:
a b c d e 
'''
3.for循环中的range使用
import time
print("for循环模仿倒计时")
#range(10,0)给出的列表为[10,9,8,7,6,5,4,3,2,1]步长为-1,及在减少
for i in range(10,0,-1):
    print(i,end="  ")
    time.sleep(1)#等待1秒
'''结果:
for循环模仿倒计时
10  9  8  7  6  5  4  3  2  1 
'''
4.Python中的循环总结
1)while是一个条件循环语句,与if声明相比,如果 if 后的条件为真,就会执行一次相应的代码块。而while中的代码块会一直循环执行,直到循环条件不再为真
2)Python提供了的另一个循环机制就是for语句,它可以遍历序列成员,可以用在列表解析和生成器表达式中,它会自动地调用迭代器的next()方法,捕获StopIteration异常并结束循环(所有这一切都是在内部发生的)。 Python的for更像是shell或是脚本语言中的foreach循环
5.切片
1)对操作对象截取其中一部分的操作,字符串、列表和元组都支持切片
切片语法:[起始:终止:步长]
从起始位置开始,结束于终止位置的前一个位置,步长为每次的变化量
2)切片练习
name = 'abcdef'
print(name[0:len(name)-1])#结束为字符串长度-1
print(name[0:-2])#将最后两个字符去掉
print(name[0::2])#默认结束为字符串长度,步长为2
'''结果:
abcde
abcd
ace
'''
6.字符串常见操作
1)find:检测str是否包含mystr,如果是返回开始索引,否则返回-1;

str = 'hello python and machine learning'
#find函数使用
print(str.find('python'),end=",")#从左查找子串的位置
print(str.rfind('python'),end=",")#从右往左找,可以用来获取文件的后缀
print(str.find('database'))#没有找到返回结果
str1 = "mypython.py"
num = str1.rfind(".")
print("文件后缀名为:"+str1[num:])
'''结果:
6,6,-1
文件后缀名为:.py
'''
2)index:和find方法一样,只是在输出时,如果没有查找到结果,则报异常;

#index使用
str = 'hello python and machine learning'
print(str.index('and'),end=",")
print(str.rindex("and"),end=",")
print(str.index("bigdata"))
'''结果:
13,13,Traceback (most recent call last):
  File "E:/Python项目/python入门/day01/num01/03.py", line 63, in <module>
    print(str.index("bigdata"))
ValueError: substring not found
'''
3)count:返回mystr在str中出现的次数
#count函数
str = 'hello python and machine learning and database'
print("字符串长度",len(str))
print("出现次数:",str.count("and"))
print(str.count("and",-20,len(str)))
'''结果:
字符串长度 46
出现次数: 2
1
'''
4)replace: 把mystr中str1替换为str2,替换次数不超过count
#replace函数
str = 'hello python and machine learning and database'
print(str.replace("and","And",1))
'''结果:
hello python And machine learning and database
'''
5)split:以分隔符mystr切片str,如果有maxsplit,则根据其大小限定分割次数
#split函数
str = 'hello python and machine learning and database'
print(str.split(' ',3))
'''结果
['hello', 'python', 'and', 'machine learning and database']
'''
6)capitalize:将字符串的第一个字母大写
title:将所有的单词首字母大写
#capitalize与title函数
str = 'hello python and machine learning and database'
print(str.capitalize())
print(str.title())
'''结果:
Hello python and machine learning and database
Hello Python And Machine Learning And Database
'''
7)startswith:检查字符串是否以str开头
endswith:是否以str结束
#startswith、endswith函数
str = "python is a popular language"
print(str.startswith('python'))
print(str.endswith("lan"))
'''结果:
True
False
'''
8)lower:将所有大写转为小写
upper:将所有小写转为大写
#lower、upper函数
str = 'Python is my love '
print(str.upper())
print(str.lower())
'''结果:
PYTHON IS MY LOVE 
python is my love 
'''
9)ljust:返回一个原字符串左对齐,并使用空格填充至长度width的新字符串
rjust:右对齐
center:居中对齐
#ljust、rjust、center
content = 'hello world'
print(content.center(30,"-"))
print(content.ljust(30,"-"))
print(content.rjust(30,"-"))
'''结果
---------hello world----------
hello world-------------------
-------------------hello world
'''
10)lstrip:删除字符串左边的空白
rstrip:右边的
strip:两端的
#lstrip、rstrip、strip
content = "   hello world  "
print(content.lstrip())
print(content.strip())
print(content.rstrip())
'''结果
hello world  
hello world
   hello world
'''
11)partition:把mystr分为三部分,str前,str,str后
rpartition:从右边开始
#partition函数
content = 'python and ipython are tools'
print(content.partition("and"))#分割
print(content.rpartition("are"))
print(content.split("and"))#相当于删除对应字符串
'''结果:
('python ', 'and', ' ipython are tools')
('python and ipython ', 'are', ' tools')#元组
['python ', ' ipython are tools']#列表
'''
12)splitlines:按照行分割,返回一个按照各行作为元素的列表
#splitlines
content = "hello\nworld"
print(content.splitlines())
'''结果:
['hello', 'world']
'''
13)isalpha:都是字母
isdigit:都是数字
isalnum:字母和数字
#isalpha,isdigit,isalnum
content = "num1andnum2123"
print(content.isalpha())
print(content.isdigit())
print(content.isalnum())
#空格和其他字符出现则为false
'''结果
False
False
True
'''
14)isspace:只包含空格
#isspace
content = " "
print(content.isspace())
'''结果
True
'''
15)join:mystr中每个字符后加str,组成新的字符串
#join函数
content = ["python","is", "a","great", "language"]
str1 = "python is good"
str = "-"
print(str.join(content))
print(str.join(str1))
'''结果:
python-is-a-great-language#元组使用结果
p-y-t-h-o-n- -i-s- -g-o-o-d#字符串使用结果
'''
16)练习1
给定一个字符串aStr,返回使用空格或者\t分割后的倒数第二个子串
#给定一个字符串aStr,返回使用空格或者\t分割后的倒数第二个子串
aStr = "The everyday we has gone is the best gift for us"
#使用空格分割
print(aStr.split(" "))
str = aStr.split(" ")
print(str[-2])
print(str.pop(-2))#等价于删除
print(str)
print(str[-2])
'''
['The', 'everyday', 'we', 'has', 'gone', 'is', 'the', 'best', 'gift', 'for', 'us']
for
for
['The', 'everyday', 'we', 'has', 'gone', 'is', 'the', 'best', 'gift', 'us']
gift
'''
7.列表
1)可以保存n个数据,数据类型可以任意
2)列表格式
name = ["张三","李四","王五"]
3)列表打印输出
#列表使用
name = ["张三","李四","王五"]
print(type(name))#类型:<class 'list'>
for temp in name:
    print(temp,end="--")
print()

len = len(name)
i = 0
while i<len:
    print(name[i],end="--")
    i+=1
#结果:张三--李四--王五--
8.练习:花名册
1)方法1
#花名册定义
nameList = ["刘翔","科比","谢霆锋","张杰","张靓颖"]
#输入查找名字
name = input("请输入你的名字:")
num = 0
#判断是否存在
for temp in nameList:
    if name == temp:
        #给出结果
        print("恭喜你,找到了")
        break
    else:
        num+=1
if num ==len(nameList):
    print("你不在花名册中")
2)方法2
#花名册定义
nameList = ["刘翔","科比","谢霆锋","张杰","张靓颖"]
#输入查找名字
name = input("请输入你的名字:")
flag = 0
#判断是否存在
for temp in nameList:
  if name==temp:
      flag = 1
      break
if flag==0:
    print("在花名册中没找到你")
else:
    print("恭喜你,找到了")
'''
请输入你的名字:谢霆锋
恭喜你,找到了
请输入你的名字:无心
在花名册中没找到你

'''

 9.列表常用操作
1)添加元素("增",append、extend、insert)
a.append使用
nameList = ["xiaoming","xiaohong","xiaohei"]
nameList.append("xiaoxin")
print(nameList)
'''结果:append添加至末尾
['xiaoming', 'xiaohong', 'xiaohei', 'xiaoxin']
'''
b.insert 使用
nameList.insert(1,"xiaoli")
print(nameList)
'''结果:insert添加至索引位置
['xiaoming', 'xiaoli', 'xiaohong', 'xiaohei']
'''
c.extend使用
nameList1 = ["laowang","laoli"]
nameList.extend(nameList1)
print(nameList)
'''结果:将一个列表添加至另一个列表末尾
['xiaoming', 'xiaohong', 'xiaohei', 'laowang', 'laoli']
'''
d.增加元素后,取元素
nameList.append(nameList1)
print(nameList)
print(nameList[len(nameList)-1][1])#取大列表中长度减1的元素,再取子列表中第二个元素
'''结果:
['xiaoming', 'xiaoli', 'xiaohong', 'xiaohei', ['laowang', 'laoli']]
laoli
'''
2)元素修改
#元素修改
nameList = ["xiaoming","xiaohong","xiaohei"]
nameList[1] = "xiaohua"
print(nameList)
'''结果
['xiaoming', 'xiaohua', 'xiaohei']
'''
3)查找元素("查",in、not in、index、count)
a.in、not in使用
#元素查找
nameList = ["xiaoming","xiaohong","xiaohei"]
name = "xioahei"
if name in nameList:
    print("没有找到名字为%s的同学"%name)
else:
    print("找到了,名字为:%s"%name)
'''结果:in和not in使用方法类似
找到了,名字为:xioahei
'''
b.index、count
nameList = ["xiaoming","xiaoming","xiaoli"]
print(nameList.index("xiaoming"),end=",")#统计该字符串第一次出现在列表中的位置
print(nameList.count("xiaoming"))#统计该字符串在列表中出现的次数
'''结果:
0,2
'''
4)删除元素("删",delete、pop、remove)
#删除元素
nameList = ["aa","bb","cc","dd"]
del nameList[1]#删除指定位置元素
print(nameList)
nameList.pop(-1)#删除指定位置元素
print(nameList)
nameList.remove("aa")#删除指定元素
print(nameList)
'''
['aa', 'cc', 'dd']
['aa', 'cc']
['aa']
'''
10.花名册练习升级版
#花名册练习改进
# 打印提示选择
print("*"*30)
print("欢迎你使用本系统")
print("1:添加新的名字")
print("2:删除指定名字")
print("3:修改名字")
print("4:查询一个名字")
print("5:查询所有人的名字")
print("0:退出系统")
print("*"*30)
#定义一个列表,存储所有的名字
nameList = []
while True:
    #获取要操作的数字
    choose = int(input("请输入选择编号:"))
    # 根据选择来做相应的事情

    if choose==1:
        #提示输入一个名字
        name1 = input("请输入新增用户名:")
        #将该用户添加到用户列表
        nameList.append(name1)
        print(nameList)
    elif choose==2:
        #输入删除的名字
        name2 = input("输入需要删除的名字:")
        #将该名字从列表中删除
        if name2 in nameList:
            nameList.remove(name2)
        else:
            print("该用户不在花名册中,无法删除")
    elif choose==3:
        #输入需要修改的名字
        name3 = input("输入需要修改的名字:")
        rename = input("输入修改后的名字:")
        #在列表中修改名字
        if name3 in nameList:
            index1 = nameList.index(name3)
            nameList[index1] = rename
        else:
            print("该用户不在花名册中,无法修改")
    elif choose ==4:
        #输入需要查询的名字
        name4 = input("输入查询的名字:")
        #给出查询结果
        if name4 in nameList:
            print("恭喜你,%s在花名册中"%name4)
        else:
            print("很遗憾,花名册中没有%s"%name4)
    elif choose ==5:
        #c查询所有人
        for name in nameList:
            print(name,end=",")
        print()
    elif choose==0:
        # 退出系统
        break
    else:
        print("你的输入不正确,请检查后重新输入!")
'''结果:
******************************
请输入选择编号:1
请输入新增用户名:谢霆锋
['谢霆锋']
请输入选择编号:1
请输入新增用户名:刘青云
['谢霆锋', '刘青云']
请输入选择编号:1
请输入新增用户名:杨幂
['谢霆锋', '刘青云', '杨幂']
请输入选择编号:2
输入需要删除的名字:杨幂
请输入选择编号:3
输入需要修改的名字:刘青云
输入修改后的名字:刘楠
请输入选择编号:5
谢霆锋,刘楠,
请输入选择编号:4
输入查询的名字:谢霆锋
恭喜你,谢霆锋在花名册中
请输入选择编号:
'''
11.列表操作:排序
#列表排序
num = [10,9,5,13,26,45,32,17]
num.sort()#升序
print(num)
num.sort(reverse=True)#降序
print(num)
num.reverse()#将列表逆序
print(num)
'''结果:
[5, 9, 10, 13, 17, 26, 32, 45]
[45, 32, 26, 17, 13, 10, 9, 5]
[5, 9, 10, 13, 17, 26, 32, 45]
'''
12.列表嵌套练习
要求:一个学校,有3个办公室,现在有8为老师等待工位的分配,编写程序随机分配
#分配办公室
import  random
#列表存储办公室
office = [[],[],[]]
#列表存储老师名字
nameList = ["A","B","C","D","E","F","G","H"]
#随机把8名老师添加到第一个列表中
for name in nameList:
    num = random.randint(0,2)
    office[num].append(name)
#按格式要求输出每个办公室的人
i = 1
for name in office:
    print("第%d个办公室的人为:"%i)
    for name1 in name:
        print(name1,end=" ")
    print()
    i+=1
'''结果:
第1个办公室的人为:
F G 
第2个办公室的人为:
A B C E H 
第3个办公室的人为:

'''
13.元组
Python中元组与列表类似,不同在于元组元素不能修改,元组使用小括号,列表为大括号;
#元组
name = ("张三",23)
print(type(name))
print(name)
'''结果:
<class 'tuple'>
('张三', 23)
'''
index、count使用与列表类似;
14.字典
1)存储
键值对存储:
不允许有两个相同的key值
{key值:values值,key值:values值.....}
#字典
nameList = {"name":"张三","sex":"男","年龄":23}
print(type(nameList))
print(nameList["name"])
'''结果:
<class 'dict'>
张三
'''
2)修改、添加、删除元素
#字典
nameList = {"name":"张三","sex":"男","年龄":23}
print(nameList["name"])
nameList["name"] = "张强"#按键值修改元素
print(nameList["name"])
nameList["weight"] = 60#添加不存在的键值对
print(nameList["weight"])
del nameList["name"]
print(nameList)
nameList.clear()
print(nameList)
'''结果:
张三
张强
60
{'sex': '男', '年龄': 23, 'weight': 60}
{}
'''
3)其他基本操作
 nameList = {"name":"张三","sex":"男","年龄":23}
print(len(nameList))#长度
print(nameList.keys())#键
print(nameList.values())#值
print(nameList.items())#返回一个含有所有键值对元组的列表
'''结果
3
dict_keys(['name', 'sex', '年龄'])
dict_values(['张三', '男', 23])
dict_items([('name', '张三'), ('sex', '男'), ('年龄', 23)])
'''
4)常用遍历
#遍历
nameList = {"name":"张三","sex":"男","年龄":23}
for key in nameList.keys():
    print(key,end=" ")
print("*"*30)
for values in nameList.values():
    print(values,end=" ")
print("*"*30)
for temp in nameList.items():
    print("%s:%s"%(temp[0],temp[1]))
print("*"*30)
for key,values in nameList.items():
    print(key,end=" ")
    print(values,end=" ")
'''
name sex 年龄 ******************************
张三 男 23 ******************************
name:张三
sex:男
年龄:23
******************************
name 张三 sex 男 年龄 23  
''' 
5)带下标索引的遍历
a.方法1
char = ["a","b","c","d"]
i = 0
for temp in char:
    print("%d %s"%(i,temp))
    i+=1
'''
0 a
1 b
2 c
3 d
''' 
b.方法2
#带下标索引的遍历
char = ["a","b","c","d"]
for num,temp in enumerate(char):
    print(num,end=" ")
    print(temp)
'''
0 a
1 b
2 c
3 d
'''
15.运算符总结:
+:合并,应用于字符串、列表、元组
*:复制,应用于字符串、列表、元组
in:元素是否存在,应用于字符串、列表、元组、字典
not in:元素是否不存在,应用于字符串、列表、元组、字典
16.Python简单内置函数
cmp(item1,item2):比较两个值
len(item):计算容器中元素个数
max(item):返回容器中元素最大值
min(item):返回容器中元素最小值
del(item):删除变量

17.学生管理系统升级(字典)

#学生管理系统# 打印提示选择print("*"*30)print("欢迎你使用本系统")print("1:添加新的用户")print("2:删除指定用户")print("3:修改用户信息")print("4:查询一个用户")print("5:查询所有用户的信息")print("0:退出系统")print("*"*30)#定义一个列表,存储所有的名字nameList = []while True:    #获取要操作的数字    choose = int(input("请输入选择编号:"))    # 根据选择来做相应的事情    if choose==1:        #提示输入一个名字        name1 = input("请输入新增用户名:")        sex1 = input("请输入新增用户性别:")        phone1 = input("请输入新增用户联系方式:")        #字典存储用户信息;名字、性别、手机号        userInfo = {}        #将用户的基本信息添加到字典中        userInfo["name"] = name1        userInfo["sex"] = sex1        userInfo["phone"] = phone1        # 将该用户添加到用户列表        nameList.append(userInfo)        print(nameList)    elif choose==2:        #输入删除的名字        name2 = input("输入需要删除的名字:")        flag = 0        #将该名字从列表中删除        for temp in nameList:             if temp["name"]==name2:                 nameList.remove(temp)                 flag = 1                 break        if flag ==0:                 print("该用户不在了名单中,无法删除")        else:                print("删除成功!")        print(nameList)    elif choose==3:        #输入需要修改的名字        name3 = input("输入需要修改的名字:")        rename = input("输入修改后的名字:")        #在列表中修改名字        for temp in nameList:            if temp["name"]==name3:                temp["name"] = rename            else:                print("用户不存在,无法修改")    elif choose ==4:        #输入需要查询的名字        name4 = input("输入查询的名字:")        #给出查询结果        for temp in nameList:            if temp["name"]==name4:                print("恭喜你,%s在花名册中"%name4)            else:                print("很遗憾,花名册中没有%s" % name4)    elif choose ==5:        #c查询所有人        for name in nameList:            print("姓名为:%s--性别为:%s--联系方式为:%s"%(name["name"],name["sex"],name["phone"]))        print()    elif choose==0:        # 退出系统        break    else:        print("你的输入不正确,请检查后重新输入!")'''结果:欢迎你使用本系统1:添加新的用户2:删除指定用户3:修改用户信息4:查询一个用户5:查询所有用户的信息0:退出系统******************************请输入选择编号:1请输入新增用户名:谢霆锋请输入新增用户性别:男请输入新增用户联系方式:10086[{'name': '谢霆锋', 'sex': '男', 'phone': '10086'}]请输入选择编号:1请输入新增用户名:张靓颖请输入新增用户性别:女请输入新增用户联系方式:1008611[{'name': '谢霆锋', 'sex': '男', 'phone': '10086'}, {'name': '张靓颖', 'sex': '女', 'phone': '1008611'}]请输入选择编号:2输入需要删除的名字:张靓颖删除成功![{'name': '谢霆锋', 'sex': '男', 'phone': '10086'}]请输入选择编号:3输入需要修改的名字:谢霆锋输入修改后的名字:锋行天下请输入选择编号:4输入查询的名字:锋行天下恭喜你,锋行天下在花名册中请输入选择编号:5姓名为:锋行天下--性别为:男--联系方式为:10086'''