基本数据类型 字符编码 文件管理

#!/usr/bin/env python
# -*- coding:utf-8 -*-


# str='a.s.d.f.g'
# l=str.split('.')
# for i in l:
# print(i,end=' ')
"""
msg='hello word'
print(msg[:2])
print(msg[::-1])
print(msg[5:0:-1])
print(len(msg))

l='ouyang is good '
print('ouyang' in l)
print('kkk' in l)



user=' ouyang '
print(user.strip())
user=' **ouyang** '
print(user.strip(' *'))


m='a:b:c:d:e:f:g'
l1=m.split(':')
print(l1)
print(l1[2])
m='a:b:c:d'
n1,n2,n3,n4=m.split(':')
print(n1,n2,n3,n4)
print(ll)
"""

user=' **ouayng** '
print(user.strip('* '))
print(user.lstrip(' *'))
print(user.rstrip(' *'))

a='hjdsHIGHJ'
print(a.lower())
print(a.upper())

l2='ouyang is good'
print(l2.startswith('ouyang'))
print(l2.endswith('good'))
#


print('my name is {},my age is {}'.format('ouayng',14))
print('my name is {x},my age is {y}'.format(x='ouayng',y=14))

l3='aa|bb|cc|dd'
print(l3.split('|'))



今日复习:

打印九九乘法表:
for i in range(1,10):
    for j in range(1,i+1):
        print("%s*%s=%s"%(i,j,i*j),end=' ')
    print()


# 打印金字塔
1 max_level=5
2 for current_level in range(1,max_level+1):
3     for j in range(max_level-current_level):
4         print(" ",end='')
5     for k in range(current_level*2-1):
6         print('*',end='')
7     print()


字符串类型:
一::基本使用
1.用途:记录描述性的状态,比如人的名字.地址,性别
2.定义方式:在"",'',""""""内包含一系类的字符
3.常用操作及内置方法:
1).按索引取值(正向取+反向取):只能取,不能改删
msg='hello word'
print(msg[1])
print(msg[-1])

2)切片(顾头不顾尾,步长)
msg='hello word'
print(msg[1:3])
print(msg)#没有改变原值

msg='hello word'
print(msg[0:5:2])
print(msg[-1:-5:-1])


了解:
msg='hello word'
print(msg[2:5:1])
print(msg[5:0:-1])
print(msg[-1::-1])

3)长度len()
msg='hello word'
print(len(msg))

4)成员运算,in和net in 判断一个子字符串是否存在于一个大的字符串中
print("alex" in 'alex is sb')
print('ouyang' not in 'alex is sb')
5)去掉字符串左右两边的字符strip 不管中间的

user='    ouyang     '
print(user.strip())
user = '  *  ouyang   '
print(user.lstrip(' *'))
user='  ouyang **  '
print(user.rstrip(' *'))
user = " **+*  */***egon*  **-*****"
print(user.strip(' *-/+'))

6) 切分split:针对按照某种分隔符组织的字符串,可以用split将其且分为列表
继而进行取值

msg="root:123456:0:0::/root:/bin/bash"
res=msg.split("/")
print(res[2])


l2 = 'ouyang:xiaohui:egon:andy'
res =l2.split(":")
print(res,res[2])

7)循环:
msg='hello'
for item in msg:
    print(item)
基本使用



重点:::::::::::重点::::::::::::重点

1strip ,lstrip,lstrip (消除多余的字符,默认为空格)
2lower,upper (将字符串里面的字符变小写,将字符串里面的字符变大写)
3startswith endswith (判断字符串开头结尾的字符是不是后面的字符)
4format()的三种玩法

a ='my name is {x},age is {y}'.format(x='andy',y='18')
print(a)
b='my name is {1},age is {0}'.format(18,"andy")
print(b)
c='my name is %s,age is %s'.format('andy',18)
print(c)


了解:
print('my name is {} my age is {}'.format(18,'egon'))
print('my name is {0} my age is {1}{1}'.format(18,'egon'))


5、split,rsplit
msg='get|a.txt|333331231'
# print(msg.split('|',1))
print(msg.split('|',1))
print(msg.rsplit('|',1))

6、join
msg='get|a.txt|333331231'
l=msg.split('|')
print(l)

src_msg='|'.join(l)#将|加入到列表l中,然后scr_msg就会变为原来的字符串
print(src_msg)


7、replace
msg='alex say i have one tesla,alex is alex hahaha'
print(msg.replace('alex','sb',1))#将alex与sb 调换 ,且调换个数为1
print(msg)

8、isdigit # 判断字符串中包含的是否为纯数字




需要了解的内置方法:
1、find,rfind,index,rindex,count
msg='hello alex is sb'
print(msg.find('alex')) #find 查找alex 在字符串中的索引
print(msg.find('alex',0,3))

print(msg.index('alex'))
print(msg.index('alex',0,3))


msg='alex aaa alex'
print(msg.find('alex'))
print(msg.rfind('alex'))

msg='alex aaa alex'
print(msg.count('alex')) # 统计一个子字符串在大字符串中出现的次数


2、center,ljust,rjust,zfill
print('egon'.center(50,'*'))
print('egon'.ljust(50,'*'))
print('egon'.rjust(50,'*'))
print('egon'.zfill(50))

3、expandtabs
print('a	b'.expandtabs(1))

4、captalize,swapcase,title
print('hello'.capitalize())
print('hElLo'.swapcase())
print('egon is nb'.title())

5、is数字系列
在python3中
num1=b'4' #bytes
num2=u'4' #unicode,python3中无需加u就是unicode
num3='' #中文数字
num4='' #罗马数字

''.isnumeric(): unicode,中文数字,罗马数字
print(num2.isnumeric())
print(num3.isnumeric())
print(num4.isnumeric())

''.isdecimal(): unicode
print(num2.isdecimal())
print(num3.isdecimal())
print(num4.isdecimal())

''.isdigit() :bytes,unicode
print(num1.isdigit())
print(num2.isdigit())
print(num3.isdigit())
print(num4.isdigit())


6、is其他
print('abc你'.isalpha()) # 字符串中包含的是字母或者中文字符

字符串中包含的是字母(中文字符)或数字
print('ab'.isalnum())
print('123123'.isalnum())
print('ab123'.isalnum())
View Code




二:该类型总结
1 存一个值

2 有序

3 不可变
x='abc'
print(id(x))
x='def'
print(id(x))



列表类型
列表类型:
一:基本使用:
1.用途:存放多个值,可以根据索引取值
2.定义方式: 在[]内用逗号分隔开多任务类型的值

l=['andy','ouyang','xiaohui']
l1=list('hello) #list就相当于调用了一个for循环依次取出'hello'的值放入列表
print("l1")


3'常用操作+内置方法
#优先掌握的操作:
#1、按索引存取值(正向存取+反向存取):即可存也可以取
#2、切片(顾头不顾尾,步长)
l=['egon','lxx','yxx',444,555,66666]
# print(l[0:5])
# print(l[0:5:2])
# print(l[::-1])

#3、长度
# l=['egon','lxx','yxx',444,555,66666,[1,2,3]]
# print(len(l))

#4、成员运算in和not in
# l=['egon','lxx','yxx',444,555,66666,[1,2,3]]
# print('lxx' in l)
# print(444 in l)

#5、追加
l=['egon','lxx','yxx']
# l.append(44444)
# l.append(55555)
# print(l)

#6、往指定索引前插入值
# l=['egon','lxx','yxx']
# l.insert(0,11111)
# print(l)
# l.insert(2,2222222)
# print(l)

#7、删除
# l=['egon','lxx','yxx']

# 单纯的删除值:
# 方式1:
# del l[1] # 通用的
# print(l)

# 方式2:
# res=l.remove('lxx') # 指定要删除的值,返回是None
# print(l,res)

# 从列表中拿走一个值
# res=l.pop(-1) # 按照索引删除值(默认是从末尾删除),返回删除的那个值
# print(l,res)

#8、循环
# l=['egon','lxx','yxx']
# for item in l:
#     print(item)

# 需要掌握的操作
l=['egon','egon','lxx','yxx',444,555,66666]
# print(l.count('egon'))
# print(l.index('egon'))
# print(l.index('yxx',0,1))
# l.clear()

# items=['a','b','c']
# items='hello'
# for item in items:
#     l.append(item)
# l.extend(items)
# print(l)

# l=['egon','egon','lxx','yxx',444,555,66666]
# l.reverse()
# print(l)

# nums=[3,-1,9,8,11]
# nums.sort(reverse=True)
# print(nums)

# items=[1,'a','b',2]
# items.sort()


#二:该类型总结
# 1 存多个值

#
# 2 有序
#
# 3 可变
# l=['a','b','c']
# print(id(l))
# l.append('d')
# print(id(l))


# 队列:先进先出
# l=[]
# # 入队
# l.append('first')
# l.append('second')
# l.append('third')
# print(l)
# # 出队
# print(l.pop(0))
# print(l.pop(0))
# print(l.pop(0))

# 堆栈:先进后出
l=[]
# 入栈
l.append('first')
l.append('second')
l.append('third')
# print(l)
# 出栈
print(l.pop())
print(l.pop())
print(l.pop())
View Code


小结在此,综上所述

基本数字类型
需要记忆
一:.数字

int  #数字
n=4
n.bit_length()  # 获取二进制的最短位数
View Code
 
二: 布尔值
"""
真或假
0或1

True
False
"""

# 三:.字符串 str

"""
s='name'
s.upper() #变大写
s.lower() # 变小写
s.title() #首字母变大写
s.strip() # 去除空白(lstrip 清除左边空白  rstrip 清除右边空白)
# 如果strip()里面的是什么就请清除什么
s.capitalize() # 首字母大写
s.center() #内容居中,(a,b) a代表的是要填补的数量,b 代表的是要填充的字符
s.rjust() #同上靠右
"""

l='hello'
print(l.center(20,'_'))   #内容居中,其他用_补齐

部分演示:
count ('a',0,4)前几位包括空格a出现了几次,子序列的个数
l='hello word'
print(l.count('l',1,5))  #输出在l 中字符'l' 出现的次数(count)


endswith ('x',0,2)   是否以x结尾,大于等于0小于2的位置    对应l.startswith()以什么开始
l='hello word'
print(l.endswith('o',1,4)) #判断在字符串l里面0到5 索引范围内是不是以o结尾
print(l.startswith('h',0,5)) #判断在字符串l里面0到5 索引范围内是不是以h开头

find (‘p’)       查找子序列,找不到返回-1
l='hello word'
print(l.find('h',0,3))  # 查看在字符串中'h'是不是在0到3 的位置,不是的话返回-1,是的话返回索引值


join   列表、元组 转 字符串
l=['lll','ooo']
s='-'.join(l)#引号里面的是什么就将用引号里面的字符连接类表或者元组里面的字符
print(s)

pertition 分割
l='hello word'
print(l.partition('ll')) #将字符串用''ll分割
replace  替换
l.split('e',1) 用e分割
l.splitlines()用换行符分割


# 索引
'''
    l='hello' 
    l[0]
    l[0:2]   切片
'''
# len(l)字符串长度
View Code



# ******************************************

# 四:.列表
n=[1,2,3,4,5,6]
n.append('name') #在列表后面追加
n.extend(['name','age','hight']) # 批量添加
n.count('name') # 计算'name'在元素中出现的次数
n.index('name') # 获取元素在列表中的索引
n.insert('1',1) #插入
n.pop(1) #删除掉索引为1的元素,如果括号里面没有值,默认删除最后一个元素
n.remove('name') #移除元素
n.reverse()  # 将列表里面的元素都翻转
del n[3]  # 删除索引为3 的元素


# 实现列表的循环
"""
li = ['电脑','试试','内容']
for item in li:
    print(item)  #item就是元素本身
"""
View Code


五:元组

特性:存多个值,有顺序,其内部的数值不能被更改,
用途: 记录多个值,当多个值没有改的需求,此时用元组
s=(1,2,3,4,5)
s.index(2,3,4) #查找元素2在范围0到3之间的索引,有就返回索引,无责报错
s.count(1) #查看元素'1'在元组里面的个数

4、成员运算in和not in
View Code



# 六:字典:
# 特性:可以存多个值,无序,可以更改
# 用途: 记录多个值,每一个值都有对应的key来描述value的作用
# 定义方式:在{}内用逗号分隔开多 个key:value,其中value可以是任意类型,
# 而key必须是不可变的类型,通常情况下应该str类型
"""
d={'name':'andy','age':18}
s='str'
l=[1,2,3]
#d.pop('name') #删除键值,并且返回对应的值
d.setdefault(s) # 将l 的值变为字典的key加入到字典中去 有责不变,无责添加
d.fromkeys(l)
d.get('name') #获取name的值
# d.clear()#清除字典的所有键值对
"""


# 循环
# d={'name':'andy','age':18}
# for k,v in d.items():
#     print(k,v)

# ****字符串与列表的互相转化****
# (1) 字符串转列表
# s="ss,dd,ff,gg"
# l=s.split(',')
# print(l)

# (2)l列表转字符串
l=['name','age']
s=''.join(l)
print(s)

(3)
# print(dir(k))          #dir  显示命令的所有用法名
# help(type('amm'))       # 显示命令的详细用法

# (4) enumerate 列表自动生成序号
l=['naem','age','hight']
for i,j in enumerate(l,1):
    print(i,j)
View Code
七:集合
#作用:去重,关系运算,

#定义:
            知识点回顾
            可变类型是不可hash类型
            不可变类型是可hash类型

#定义集合:
            集合:可以包含多个元素,用逗号分割,
            集合的元素遵循三个原则:
             1:每个元素必须是不可变类型(可hash,可作为字典的key)
             2:没有重复的元素
             3:无序

注意集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值
 

#优先掌握的操作:
#1、长度len
#2、成员运算in和not in

#3、|合集
#4、&交集
#5、-差集
#6、^对称差集
#7、==
#8、父集:>,>= 
#9、子集:<,<=  


字符编码
1 http://www.cnblogs.com/linhaifeng/articles/5950339.html

文件管理及指针

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 上节课复习:
1.字符编码:
1.1 如何解决乱码的问题:
    字符存取使用的编码标准不一样
1.2 头文件
在文件的首行写入文件头,用于控制python解释器读取py文件是使用的编码
#coding:文件当时写入磁盘时使用的编码标准

1.3 关于字符串类型(只有在运行python程序的第三阶段才有字符串的概念)
编码的问题python3中的字符串str/字节串bytes类型
str===unicode 就是说Unicode就是字符串类型


bytes  res=s.encode('gbk')  unicode -----编码----gbk
bytes  res-s.decode('gbk')  gbk ------解码------unicode

1.4文件处理
    1什么是文件:
        文件是操作系统提供给用户/应用程序用于间接地操作硬盘的抽象的单位
   2 为什么要用文件
        为了将应用程序内存的数据永久保存到硬盘
    3.如何用文件:
        1.打开文件
            f=open('a.txt','r',encoding='utf-8')
        2.读/写操作
            f.read()
            f.write()
        3.关闭文件
            f.close()
        控制操作文件的两种模式(不能单独使用,必须与rwa连用)
            t:读写文件都是以字符串为单位,必须指定encoding的参数
            b:读写都是以bytes类型为单位的,必须不指定encoding的参数
        打开文件的三种模式
            r:只读模式
            w:只写模式
            a:只追加模式


f=open(r'b.txt'.mode='wb')
f.write('你好',encode('jbk'))
f.close()


f=ope('b.txt',mode='rb')
msg=f.read()
 print(type(msg))
 print(type(msg.decode('gbk')))
 f.close()



 可读可写
# r+t

# w+t

# a+t

 with open('a.txt',mode='r+t',encoding='utf-8')as f1:
     msg=f.readline()
     print(msg)
     f.write('ssssssssd')


指针
# 控制文件内指针的移动
# 文件内指针的移动,只有t模式下的read(n),n 代表的字符的个数
# 除此以外的文件内指针的移动都是以字节为单位

# with open('a.txt','r+',mode='rb')as f:
#     msg=f.read(3)
#     print(msg.decode('utf-8'))

f.seek(offset,whence)有两个参;
offset 控制指针移动的字节数
whence 代表参照什么位置进行移动
    whence =0 代表参照文件开头(默认的) 可以在t和b模式下使用
    whence=0  代表参照当前所在位置,必须在b模式下进行
    whence = 0 代表参照文件末尾,必须在b模式下进行

with open('a.txt',mode='rt',encoding='utf-8') as f:
    f.seek(6,0)
    msg=f.read(1)
    print(msg)

with open('a.txt', mode='rb', encoding='utf-8') as f:
    f.seek(3,0)
    msg=f.read(3)
    print(msg.decode('utf-8'))

    with open('a.txt',mode='rb') as f:
        # f.seek(0,2)
        # print(f.tell())
        f.seek(-3,2)
        msg=f.read(3)
        print(msg.decode('utf-8'))

    # with open('c.txt','r+t',encoding='utf-8') as f:
    #     f.seek(13,0)
    #     # f.write('在老男孩')
    #     f.write('h')

    # 修改文件的方式一:
    # 1 将文件内容由硬盘全部读入内存
    # 2 在内存中完成修改
    # 3 将内存中修改后的结果覆盖写回硬盘

    # with open('d.txt',mode='rt',encoding='utf-8') as f:
    #     all_data=f.read()

    # print(all_data,type(all_data))

    # with open('d.txt',mode='wt',encoding='utf-8') as f:
    #     f.write(all_data.replace('alex','dsb'))

    # 错误的做法
    # with open('d.txt',mode='rt',encoding='utf-8') as f1,open('d.txt',mode='wt',encoding='utf-8') as f2:
    #     all_data=f1.read()
    #     f2.write(all_data.replace('dsb','alex'))

    # 修改文件的方式二:
    # 1 以读的方式打开源文件,以写的方式打开一个临时文件
    # 2 从源文件中每读一样内容修改完毕后写入临时文件,直到源文件读取完毕
    # 3 删掉源文件,将临时文件重命名为源文件名
    # import os
    #
    # with open('d.txt',mode='rt',encoding='utf-8') as read_f,open('.d.txt.swap',mode='wt',encoding='utf-8') as write_f:
    #     for line in read_f:
    #         write_f.write(line.replace('alex','dsb'))
    #
    # os.remove('d.txt')
    # os.rename('.d.txt.swap','d.txt')

    # 方式一:
    # 优点: 在文件修改的过程中硬盘上始终一份数据
    # 缺点: 占用内存过多,不适用于大文件

    # 方式二:
    # 优点: 同一时刻在内存中只存在源文件的一行内容,不会过多地占用内存
    # 缺点: 在文件修改的过程中会出现源文件与临时文件共存,硬盘上同一时刻会有两份数据,即在修改的过程中会过多的占用硬盘,
View Code






原文地址:https://www.cnblogs.com/ouyang99-/p/9360089.html