C语言基础学习PYTHON——基础学习D02

20180801内容纲要:

  1 字符串的系列操作

  2 集合

  3  文件的读写

  4 字符编码转换

  5 小结

  6 练习:三级菜单(有彩蛋)

1 字符串的系列操作

特性:不可修改。('str' object does not support item assignment)

支持运算:切片、索引、min()、max()、len()等

关于字符串的操作:

#关于字符串的一些操作
'''
name = "zhang\tkanghui" print(name.capitalize()) #capitalize首字母大写
print(name.count("a")) #count计数
print(name.center(,"-")) #center(,“-”)表示总共50个字符,输出占中间位置
print(name.encode())
print(name.endswith("ui")) #判断是不是以ui结尾
print(name.expandtabs(tabsize=)) #将tab在输出时转成相应数量的空格
print(name.find("kang")) #找到字符开头的索引
''' name ="my name is {name} and i am {year} old"
print(name.format(name='zhangkanghui',year=)) #格式化输出
print(name.format_map( {'name':'zhangkagnhui','year':} )) #以字典形式格式化输出
print(name.isdigit()) #判断是否为数字
print(name.isalnum()) #判段是否为阿拉伯
print('abc12/'.isalnum())
print(name.isalpha()) #判断是否为纯英语字母
print('Aa'.isalpha())
print(name.isdecimal()) #判断是否为十进制
print(name.isidentifier()) #判断是否为合法标识符
print(' ab'.isidentifier())
print(name.islower())
print(name.isnumeric())
print('1.2'.isnumeric()) #判断是否为纯数字,小数点也不行
print(name.isspace()) #判断是否为空格
print(name.istitle()) #判断是否为标题,即每个都是首字母大写开头
print(name.isprintable()) #判断是否可打印,tty file,drive file
print(name.isupper()) #判断是否全部为大写
print('+'.join(['','','']))
print(name.ljust(,'*')) #总长为50,左侧开始
print(name.rjust(,'-')) #总长为50,右侧开始
print(name.lower()) #把大写变成小写
print(name.upper()) #把小写变成大写
print(name.lstrip())
print(name.strip()) #去掉两头的空格和回车
print(name.rstrip())
p =str.maketrans('abc','')
print("alex li".translate(p))
print("alex li".replace('l','L',))
print("alex li".rfind('l')) #查找右侧的
print("alex li".split()) #把字符串以空格分离,以列表输出
print("alex li".split('l')) #把字符串以l分
print("1+\n2+3".splitlines()) #去除换行符
print("alex Li".swapcase()) #小写换大写,大写换小写
print("alex li".title()) #变成标题,即每个首字母大写
print(name.zfill())

2 集合(set)

集合是一个无序、不可重复的数据组合。(字符和元组属于不可变序列,而列表支持插入、删除和替换元素;所有的序列都支持迭代;字典dict是无序的,且key必须是唯一的)

用途:

(1)去重:把一个列表变成一个集合。

list_1 = [1,2,4,5,6,2,1,]
list_1 =set(list_1)
print(list_1,type(list_1)) #集合无序、不重复

(2)关系测试:交集、并集、差集、子集、父集、对称差集

运算符:

&交集

|并集

-差集    例:t-a  在t中不在a中

^对称差集(除去交集对称的部分)

<=子集    例:a<=t测试是否a中的每一个元素都在t中

>=父集

list_2 =set([0,66,222,4,6])
print(list_1,list_2)
#交集intersection
print(list_1.intersection(list_2))
#并集union
print(list_1.union(list_2))
#差集differeence in list_1 but not in list_2
print(list_1.difference(list_2))
print(list_2.difference(list_1))
#子集issubset
print(list_1.issubset(list_2))
#父集isupperset
print(list_1.issubset(list_2))
#对称差集
print(list_1.symmetric_difference(list_2)) list_3 =set([1,2,3])
list_4 =set([4,5,6])
print(list_3.isdisjoint(list_4)) #没有交集返回True

集合的基本操作:

#基本操作
list_3.add(999)
print(list_3)
list_3.update([777,888,999])
print(list_3)
print(list_3.pop())
print(list_3.pop())
print(list_3.pop())
print(list_3.pop())

还有一些不常用的,比如:

.remove Remove and return an arbitrary set element.

.discard Remove an element from a set if it is a menber. If the element is not a menber, do nothing.

3 文件(file)

现有如下文件(热爱生命——汪国真):

 我不去想是否能够成功
既然选择了远方
便只顾风雨兼程
我不去想能否赢得爱情 既然钟情于玫瑰
就勇敢地吐露真诚
我不去想身后会不会袭来寒风冷雨
既然目标是地平线
留给世界的只能是背影
我不去想未来是平坦还是泥泞
只要热爱生命 一切,都在意料之中

(1)文件的打开模式

  • r,只读模式(默认)
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】
 '''
data =open("yesterday",encoding="utf-8").read()
#1encoding:windows默认GBK
#2'r'只能读;'w'只能写,且是创建一个新的文件,如果文件名已存在,则会覆盖;'a'只能写,append追加补充不会覆盖源文件
print(data)
'''
#f =open("yesterday",'r',encoding="utf-8")
#f =open("yesterday",'w',encoding="utf-8")
#f =open("yesterday",'a',encoding="utf-8")
'''
f =open("yesterday",encoding="utf-8") #赋给f一个内存对象,又叫文件件句柄
data =f.read()
print(data)
'''
  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
 #读写'r+'读和追加,能读能写,但是写只能在尾部追加无论读取光标的位置在哪
f =open("yesterday2",'r+',encoding="utf-8")
print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell())
f.write("-------NB--------") #写读'w+'能写能读,创建新文件写,读仍然是在为不追加,无论读取光标位置
f =open("yesterday2",'w+',encoding="utf-8")
f.write("-------NB--------\n")
f.write("-------NB--------\n")
f.write("-------NB--------\n")
print(f.tell())
f.seek(10)
print(f.readline())
f.write("should be at the begining of the second line")
f.close()
'''
#追加读写'a+'

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件

  • rb
  • wb
  • ab

二进制文件的读取:

 #Author:ZhangKanghui

 '''
#'rb'二进制。视频以二进制读取。
f =open("yesterday2",'rb')
print(f.readline())
'''
f =open("yesterday2",'wb')
f.write("Hello world\n".encode()) #二进制便把文件str转换成byte用encode()

等等,还有~with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:
....

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

(2)文件的读取

读取前五行:

 #读取前五行
'''
f =open("yesterday",encoding="utf-8") for i in range(5):
print(f.readline()) print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())

不读取第十行:

 #不读取第十行
#f =open("yesterday",encoding="utf-8")
#low bige loop
'''
#print(f.readlines()) #把文件读取成一个列表,但这种方法只适合小文件读取
#for line in f.readlines():
for index,line in enumerate(f.readlines()):
if index == 9:
print("-----我是分割线-----")
continue
print(line.strip()) #若不换行, .strip去除换行符
'''
#high bige loop
'''
count = 0
for line in f:
if count ==9:
print("------我是分割线-------")
count += 1
continue
print(line) #这种文件的读取方式效率最高,一行一行的读,内存对象一直都只有一行
count +=1

重新读取文件:

f.read()读取文件时,从头到尾。再次读取文件时需要先将读取位置光标调到开头。

f.tell()  文件读取位置,打印当前读取光标位置

f.seek() 寻找当前读取光标位置

 #重新读取文件
print(f.tell()) #文件读取光标位置
#print(f.read(50))
#print(f.tell())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell())
f.seek(0) #文件读取光标移到0,经常与.tell联合使用,以便再次读取文件 print(f.encoding) #数据编码

(3)文件的操作

a 截取

 #截取truncate
f =open("yesterday",'a',encoding="utf-8")
f.truncate(10) #无论读取光标在哪都是从头开始截取

b 修改

 #Author:ZhangKanghui

 f =open("热爱生命",'r',encoding="utf-8")
f_new =open("热爱生命.bak",'w',encoding="utf-8") for line in f:
if "我不去想能否赢得爱情" in line:
line =line.replace("我","你")
f_new.write(line)
f.close()
f_new.close()

(4)文件关闭

f.close()

4 字符编码的转换

核心:Unicode,默认中英文都是2个字节16位

Utf-8可变长的字符编码,所有英文字符按ASCII码1个字节8位,中文3个字节。中国有钱~

详细文章:

http://www.cnblogs.com/yuanchenqi/articles/5956943.html

http://www.diveintopython3.net/strings.html

再来说说Python3中字符编码

  1 python3默认文件编码是utf-8

  2 声明变量默认编码是unicode

  3 str和bytes做了明确的区分。bytes就是2进制流,因为python对数据进行操作做了一层封装,否则让你直接看到一堆2进制,你能看出哪个字符对应哪段2进制么?

    

5 小结

字符编码的理解很关键~

发现插入代码折叠功能~

编程真的是和很难!

6 练习

多级菜单

要求:

  • 三级菜单
  • 可依次进入各子菜单
  • 所需知识点:列表、字典

两种答案:

 #Author:ZhangKanghui

 data ={
'北京':{
"朝阳":{
"望京":["奔驰","陌陌"],
"国贸":["CICC","HP"],
"东直门":["Advent","飞信"],
},
"昌平":{
"沙河":["old boy","test"],
"天通苑":["链家地产","我爱我家"],
},
"海淀": {},
},
'山东':{
"德州":{},
"青岛":{},
"济南":{},
},
'广东':{
"常熟":{},
"东莞":{},
"惠州":{},
},
} '''
while True:
for i1 in data:
print(i1)
choice =input("选择进入1>>:")
if choice in data:
while True:
for i2 in data[choice]:
print("\t\t",i2)
choice2 =input("选择进入2>>:")
if choice2 in data[choice]:
while True:
for i3 in data[choice][choice2]:
print("\t\t\t\t",i3)
choice3 =input("选择进入3>>:")
if choice3 in data[choice][choice2]:
for i4 in data[choice][choice2][choice3]:
print("\t\t\t\t\t\t",i4)
choice4 =input("最后一层,按b返回>>:")
if choice4 =='b':
pass
if choice3 == 'b':
break
if choice2 == 'b':
break
'''
#为了实现在每一级都能退出 将True换掉
exit_tag = False while not exit_tag:
for i1 in data:
print(i1)
choice =input("选择进入1>>:")
if choice in data:
while not exit_tag:
for i2 in data[choice]:
print("\t\t",i2)
choice2 =input("选择进入2>>:")
if choice2 in data[choice]:
while not exit_tag:
for i3 in data[choice][choice2]:
print("\t\t\t\t",i3)
choice3 =input("选择进入3>>:")
if choice3 in data[choice][choice2]:
for i4 in data[choice][choice2][choice3]:
print("\t\t\t\t\t\t",i4)
choice4 =input("最后一层,按b返回>>:")
if choice4 =='b':
pass
elif choice4 =='q':
exit_tag =True
if choice3 == 'b':
break
elif choice3 == 'q':
exit_tag = True
if choice2 == 'b':
break
elif choice2 == 'q':
exit_tag = True
 #Author:ZhangKanghui

 data ={
'北京':{
"朝阳":{
"望京":["奔驰","陌陌"],
"国贸":["CICC","HP"],
"东直门":["Advent","飞信"],
},
"昌平":{
"沙河":["old boy","test"],
"天通苑":["链家地产","我爱我家"],
},
"海淀": {},
},
'山东':{
"德州":{},
"青岛":{},
"济南":{},
},
'广东':{
"常熟":{},
"东莞":{},
"惠州":{},
},
} while True:
for i1 in data:
print(i1)
choice =input("选择进入1>>:")
if choice in data:
while True:
for i2 in data[choice]:
print("\t\t",i2)
choice2 =input("选择进入2>>:")
if choice2 == 'b':
break
if choice2 in data[choice]:
while True:
for i3 in data[choice][choice2]:
print("\t\t\t\t",i3)
choice3 =input("选择进入3>>:")
if choice3 == 'b':
break
if i3 in data[choice][choice2]:
while True:
for i4 in data[choice][choice2][choice3]:
print("\t\t\t\t\t\t",i4)
choice4 =input("最后一层,按b返回>>:")
if choice4 =='b':
break

这是尾巴:

最后推荐一个链接:我要自学网,不让打广告只能植入图片了。点击进入学习可以给我加V币。

内容丰富免费

这是随笔~

D02——C语言基础学PYTHON的更多相关文章

  1. D10——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D10 20180906内容纲要: 1.协程 (1)yield (2)greenlet (3)gevent (4)gevent实现单线程下socket多并发 2. ...

  2. D16——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D16 20180927内容纲要: 1.JavaScript介绍 2.JavaScript功能介绍 3.JavaScript变量 4.Dom操作 a.获取标签 b ...

  3. D15——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D15 20180926内容纲要: 1.CSS介绍 2.CSS的四种引入方式 3.CSS选择器 4.CSS常用属性 5.小结 6.练习 1 CSS介绍 层叠样式表 ...

  4. D07——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D07 20180826内容纲要: 面向对象进阶学习 1 静态方法 2 类方法 3 属性方法 4 类的特殊成员方法(本节重点) 5 反射(本节重点) 6 异常(本 ...

  5. D06——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D06 20180821内容纲要: 面向对象初级学习 1 面向对象 2 类 (1)封装 (2)继承 (3)多态 3 小结 4 练习:选课系统 5 课外拓展:答题系 ...

  6. D05——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D05 20180815内容纲要: 1 模块 2 包 3 import的本质 4 内置模块详解 (1)time&datetime (2)datetime ...

  7. D17——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D17 20181014内容纲要: 1.jQuery介绍 2.jQuery功能介绍 (1)jQuery的引入方式 (2)选择器 (3)筛选 (4)文本操作 (5) ...

  8. D14——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D14 20180919内容纲要: 1.html认识 2.常用标签 3.京东html 4.小结 5.练习(简易淘宝html) 1.html初识(HyperText ...

  9. D13——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D13 20180918内容纲要: 堡垒机运维开发 1.堡垒机的介绍 2.堡垒机的架构 3.小结 4.堡垒机的功能实现需求 1 堡垒机的介绍 百度百科 随着信息安 ...

随机推荐

  1. Castle ActiveRecord学习(八)事务

    代码: public void UpdateThemeInfo(int id) { //事务 using (TransactionScope ctran = new TransactionScope( ...

  2. DALSA网口线扫相机SDK开发详解例程(C#版)

    首先吐槽一句,官方的demos写的真的不好,坑爹啊.对于小白来说,开发官方demos为我所用太难了.为什么呢?因为它Dalsa的DALSA.SaperaLT.SapClassBasic.dll中,不仅 ...

  3. Golang之继承,多重继承(struct)

    热乎的代码来了 package main import "fmt" /* 继承 一个结构体嵌到另一个结构体,称作组合 匿名和组合的区别 如果一个struct嵌套了另一个匿名结构体, ...

  4. [SoapUI]怎样获取隐藏元素的文本内容Get text of hidden element

    隐藏元素无法通过gettext()获取其文本内容,须用javascript来获取 String actualDataPointName = (String) ((JavascriptExecutor) ...

  5. 数据挖掘中ID3算法实现zz

    id3 function D = ID3(train_features, train_targets, params, region) % Classify using Quinlan's ID3 a ...

  6. LCD相关基础知识

    1.什么是LCD? (1)LCD(Liquid Crystal Display)俗称液晶.液晶是一种材料,液晶这种材料具有一种特点:可以在电信号的驱动下液晶分子进行旋转,旋转时会影响透光性, 因此我们 ...

  7. mysql 更新替换字符串

    update zxg set newlevel = REPLACE(newlevel,'b','') 把表zxg中的newlevel字段中的b删除

  8. 书籍索引 #C++

    卷 计算机 的文件夹 PATH 列表卷序列号为 00000200 0001:8890F:.│ 21天学通C++.pdf│ C++ Primer Plus 第6版 中文版.pdf│ C++ Templa ...

  9. linux每天一小步---awk命令详解

    1 命令功能 awk是linux环境下的一个强大的文本工具,由于awk天生提供对文件中文本分列进行处理,所以如果一个文件中的每行都被特定的分隔符(默认为空格)隔开,我们就可以将这个文件看成是有很多列的 ...

  10. 项目中使用WCF替换asmx Web service总结

    以前项目解决方案中,用http协议的asmx Web service作服务器数据访问入口,在SoapHeader中写入用户名和加盐密码进行身份认证. http asmx服务是明文传输,传输过程中数据很 ...