基础数据类型补充

  • str
#首字母大写 其他小写
s1 = 'sABcDEF'
print(s1.capitalize()) #return  Sabcdef
#大小写翻转
s1 = 'sABcDEF'
print(s1.swapcase()) #return  SabCdef
#每个单词首字母大写,非字母隔开的也算2个单词,
s1 = 'hello world'
print(s1.title()) #return  Hello World
#居中填充
s1 = 'hello world'
print(s1.center(30,'*')) #return  *********hello world**********
#find找字符,找到第一个就返回,找不到返回 -1
s1 = 'hello world'
print(s1.find('l')) #return 2 
#index 找字符,找到第一个就返回,找不到就报错
s1 = 'hello world'
print(s1.index('m')) #return ValueError: substring not found
  • tuple 元组

    • 元组创建的时候只有一个元素,结果与元素类型一致
    tu1 = (2)
    print(tu1,type(tu1))  #return 2 <class 'int'>  #int 省略掉了?
    
    • count()元组计数
    tu1 = (2,4,4,5,5,5,5)
    print(tu1.count(5)) #return 4
    
    • 返回元组元素位置 index
    tu1 = (2,4,4,5,5,5,5)
    print(tu1.index(4)) #return 1
    
  • sort()排序

    l1 = [1,4,2,8,7,9,0]
    l1.sort(reverse=True) #从大到小排列
    print(l1)  #return  [9, 8, 7, 4, 2, 1, 0]
    
  • reverse()转置

l1 = [1,4,2,8,7,9,0]
l1.reverse()
print(l1)  #return [0, 9, 7, 8, 2, 4, 1]
  • 列表相加 + 相乘 *
l1 = [1,4,2,8,7,9,0]
l2 = ['hello','world']
print(l1+l2)  #return  [1, 4, 2, 8, 7, 9, 0, 'hello', 'world']
l2 = ['hello']
print(l2*3)  #return  ['hello', 'hello', 'hello']
#列表 删除索引为奇数的值,for循环按照索引删除会得到错误结果
l1 = [11,22,33,44,55]
del l1[1::2]
print(l1) #return [11, 33, 55]
  • 循环一个列表时,最好不要改变列表的大小,元素索引会变化

  • 字典dict 补充

#update()
dic = {'name':'tom','age':18}
dic.update(hight=178)
print(dic) #return {'name': 'tom', 'age': 18, 'hight': 178}
#元组的拆包添加到字典
dic = {'name':'tom','age':18}
dic.update([('hobby','dance'),('grade',3),('score',98)])
print(dic) #return  {'name': 'tom', 'age': 18, 'hobby': 'dance', 'grade': 3, 'score': 98}
dic = {'name':'tom','age':18}
dic2 = {'name':'jerry','hobby':'dance'}
dic.update(dic2) #有则覆盖,无则添加
print(dic) #return  {'name': 'jerry', 'age': 18, 'hobby': 'dance'},名字被更新了 
#删除字典dic 键中含有a字母的元素 定义一个新的
dic = {'name':'tom','age':18,'hobby':'dance'}
dic2 = {}
for key,value in dic.items():
    if 'a' not in key:
        dic2[key]=value
dic = dic2
print(dic) #return {'hobby': 'dance'}循环一个字典时,不能改变字典的大小 
#删除字典dic 键中含有a字母的元素 报错
dic = {'name':'tom','age':18,'hobby':'dance'}
dic2 = dic
for key in dic:
    if 'a' in key:
        dic2.pop(key)
dic = dic2
print(dic) #return RuntimeError: dictionary changed size during iteration 
#删除字典dic 键中含有a字母的元素 报错
dic = {'name':'tom','age':18,'hobby':'dance'}
dic2 = dic
for key in dic.keys():
    if 'a' in key:
        dic2.pop(key)
dic = dic2
print(dic) #return RuntimeError: dictionary changed size during iteration
#删除字典dic 键中含有a字母的元素 成功
dic = {'name':'tom','age':18,'hobby':'dance'}
dic2 = dic
for key in list(dic.keys()): #把keys 转换成了列表中的元素
    if 'a' in key:
        dic2.pop(key)
dic = dic2
print(dic) #return {'hobby': 'dance'} 成功

编码的进阶

  • 数据在内存中全部是以Unicode编码的,但是数据用于网络的传输或者存储到硬盘中,必须是以非Unicode编码(utf-8 ,gbk等)

    • str = 'hello'
      • 在内存中是以Unicode编码的
    • b = b'hello' #前面加个b就是bytes类型
      • 在内存中是以非Unicode编码的
  • 数据发送和存储都要转化成bytes类型

  • str 与 bytes的转换

#unicode 与 utf-8 转换
s1 = '中国'
b1 = s1.encode('utf-8') #utf-8编码
print(b1,type(b1))  #return  b'\xe4\xb8\xad\xe5\x9b\xbd'  <class 'bytes'>

b2 = b'\xe4\xb8\xad\xe5\x9b\xbd'
s2 = b2.decode('utf-8') #解码
print(s2) #return 中国
#unicode 与 gbk的转换
s1 = '中国'
b1 = s1.encode('gbk') #gbk编码
print(b1,type(b1))  #return  b'\xd6\xd0\xb9\xfa' <class 'bytes'>   #gbk的模式就变成了2个字节

b2 = b'\xd6\xd0\xb9\xfa'
s2 = b2.decode('gbk')
print(s2) #return 中国
#gbk转化utf-8  ****重要****
b1 = b'\xd6\xd0\xb9\xfa'
u1 = b1.decode('gbk')
b2 = u1.encode('utf-8')
print(b2)

文件的操作file

  • 文件打开基本步骤

    • 文件的路径
    • 打开的方式
    • 编码格式:utf-8
    f = open(r'f:\python\test.txt',encoding='utf-8',mode='r')
    content = f.read()
    print(content)
    f.close()
    
  • open()是python的一个内置函数,操作文件的,底层调用的是操作系统的接口,操作系统有一个打开文件的接口

  • f 是文件句柄,我们定义的一个变量,对文件的任何操作都通过这个句柄

  • encoding可以不写,不写代表操作系统默认的编码本,windows默认编码是gbk ,win10 应该是utf-8,linux 是 utf-8 ,OS 默认是utf-8

  • mode 不写 默认是读

  • close(),每次操作完文件都要关闭

  • UnicodeDecodeError: 文件存储时与文件打开时用的不同编码本

  • 路径加r 就可以避免歧义

文件的读 r

  • r,rb(操作非文本类文件),r+(只能先读,后写),r+b

  • r :

    • 全读
    f = open(r'f:\python\test.txt',mode='r')
    content = f.read(1)
    print(content) #return test
    f.close()
    
    • 按字符个数读
    f = open(r'f:\python\test.txt',mode='r')
    content = f.read(2) #读2个字符
    print(content)  #return te
    f.close()
    
    • 按行读
    f = open(r'f:\python\test.txt',mode='r')
    print(f.readline()) #return 返回第一行
    print(f.readline()) #return 返回第二行
    f.close()
    
    • 按行全读
    f = open(r'f:\python\test.txt',mode='r')
    print(f.readlines())
    f.close() #return ['test\n', 'sdfsd\n', 'sfsdfsdfsdf\n']
    
    • 循环读
    f = open(r'f:\python\test.txt',mode='r')
    for line in f:
        print(line) #return 逐行打印
    f.close() 
    
    • 读图片rb格式
    f = open(r'f:\python\aa.jpg',mode='rb')
    print(f.read())  #return b'\xff\xd8\xff\xe0\x00\x10JFIF\x0。。。。。。。。
    f.close()
    

文件的写 w

f = open('test2.txt',encoding='utf-8',mode='w')
f.write('hello world') #相对路径下,没有文件就创建文件并写入,原来有文件,就把内容覆盖
f.close()
  • 写一个图片
f = open('aa.jpg',mode='rb')
content = f.read()
f.close()

f2 = open('bb.jpg',mode='wb')
f2.write(content)  #生成一个同样的图片
f2.close()

文件的追加 a 四种模式

f = open('test.txt',mode='a')
f.write('lllllll') #最后加 ,没有文件就新建文件
f.close()

f.tell()可以返回光标的位置

f.seek()调整光标的位置,可以应用到从哪里开始读文件 ,网络里有断点续传要用到这个功能

f.flush()强制刷新保存,通常在write()后面用

打开文件的另一种方式

  • with
# 不用手动关闭文件,在一定时间自动关闭,
with open('test.txt',encoding='utf-8') as f1:
    print(f1.read())
#同时多个文件的读写
with open('test.txt',encoding='utf-8') as f1,\
    open('test2.txt',encoding='utf-8',mode='w') as f2:
    print(f1.read())
    f2.write('hello')

文件的改的操作

  • 改文件的步骤
    • 以读的模式打开源文件
    • 以写的模式创建一个新文件
    • 将原文件的内容读出来修改成新内容,写入新文件
    • 将原文件删除
    • 将新文件重命名成原文件
#改文件
import os
with open('tom的介绍.txt',encoding='utf-8',mode = 'r') as f1,\
    open('tom的介绍1.txt',encoding='utf-8',mode = 'w') as f2:
    content = f1.read() #但是全读 如果文件很大,占用内存也大
    content = content.replace('tom','Tom') #小写tom 改成了Tom
    f2.write(content)
os.remove('tom的介绍.txt')
os.rename('tom的介绍1.txt','tom的介绍.txt')
#改进一下
import os
with open('tom的介绍.txt',encoding='utf-8',mode = 'r') as f1,\
    open('tom的介绍1.txt',encoding='utf-8',mode = 'w') as f2:
    for line in f1: #按行循环
        new_line =line.replace('Tom','tom')
        f2.write(new_line)
os.remove('tom的介绍.txt')
os.rename('tom的介绍1.txt','tom的介绍.txt')

测试

#判断输入的数字是不是水仙花数

num = input('Entry a num:')
sum=0
if num.isdecimal(): #判断是纯数字
    for i in num:
        sum+=int(i)**3
    if sum == int(num):print('yes')
    else:print('no')
else:print('请输入纯数字')
posted on 2020-07-05 21:24  94小渣渣  阅读(102)  评论(0)    收藏  举报