python_day02 基本数据类型操作,字符编码,文件处理

当天要学习知识点:

1、基本数据类型

2、字符编码

3、文件处理

1、基本数据类型

数字型、字符串、列表、元组、集合

数字型

#整型
age=10 #age=int(10)
print(type(age))
#浮点型
salary=3000.3 #salary=float(3000.3)
print(type(salary))
#复数
x=1-2j
print(x.real)
print(x.imag)
#机制间转换
age=10 #age=int(10)
print(bin(age)) #10->2
#1010 1*(2**3)+1*2=10
print(oct(age)) #10-8
print(hex(age)) #10-16
'''
0b1010
0o12
0xa
'''

字符串str:

st='hello nice to meet you Name:{name},Age:{age}    '
print(st[0])       #取值
# 字符串st的常用操作
print(st[1:9:2])      #切片 步长为2
print(st.stip())  #去掉字符串前后空格
print(st.split())  #分割 可指定分割符为*或|
print(len(st))     #长度
# 字符串st的其他操作
print(st.upper())  #大写
print(st.lower())  #小写
print(st.center(60,'*'))     #指定字符个数,字符串居中,其他*补全
print(st.count('o'))   #统计指定字符的个数,空格也算是一个字符
print(st.find('o'))    #列出'o'所在位置信息,不存在输出为-1
print(st.index('o'))   #列出'o'所在位置信息,不存在则报错
print(st.format(name='liwj',age='17'))     #格式化字符串,替代{}中的内容
print(st.replace('o','O',2))   #替换指定字符为其他字符,可指定替换次数
print(st.startswith('h'))      #判断字符串开头和结尾信息
print(st.endswith('o'))
print(st.isdigit())    #判断字符串中字符是否是为数字
结果信息:
h
el i
hello nice to meet you Name:{name},Age:{age}
['hello', 'nice', 'to', 'meet', 'you', 'Name:{name},Age:{age}']
48
HELLO NICE TO MEET YOU NAME:{NAME},AGE:{AGE}    
hello nice to meet you name:{name},age:{age}    
******hello nice to meet you Name:{name},Age:{age}    ******
3
4
4
hello nice to meet you Name:liwj,Age:17    
hellO nice tO meet you Name:{name},Age:{age}    
True
False
False
#字符串定义
name='egon' # ==name=str('egon')
print(type(name))
print(name)
#字符串常用操作--优先掌握
#索引
name='egon' #name=str('egon')
print(name[0])
print(name[1000]) #超出索引值会报错#移除空白
name=' egon '
name=name.strip()
print(name)
name='***egon********'
print(name.strip('*'))
print(name.lstrip('*'))
print(name.rstrip('*'))
#切分
user_info='root:x:0:0::/root:/bin/bash'
print(user_info.split(':')[5])
cmd_info='get|a.txt|333333333'
print(cmd_info.split('|')[0])
print(cmd_info.split('|',1)[0])
msg='name egon age 18'
print(msg.split())
#取长度
name='egon'
print(name.__len__())
print(len(name)) # ==name.__len__()
#切出子字符串
name='hello world'
print(name[1:7:2])
#字符串的其他方法(掌握)
name='alex_SB'
#startwith,endwith
print(name.endswith('SB'))
print(name.startswith('alex'))
name='alex say :i have one tesla,my name is alex'
#replace替换字符用法
print(name.replace('alex','SB',1))
#格式化输出信息
print('{} {} {}'.format('egon',18,'male'))
print('{0} {1} {0}'.format('egon',18,'male'))
print('NAME:{name} AGE:{age} SEX:{sex}'.format(age=18,sex='male',name='egon'))
#isdigit判断内容是否是数字
num='123'
print(num.isdigit())
oldboy_age=73
while True:
age=input('>>: ').strip()
if len(age) == 0:continue
if age.isdigit():
age=int(age)
print(age,type(age))


 
 
列表list:
li=['liwj','egon','han',1,2,3,'abc']
print(li)
print(li[1:9:2])      #切片 步长为2
li.append('add')     #列表中添加内容
print(li)
li.pop()          #默认从后面删除,可以指定位置进行删除,li.pop(1)
print(li)
li.insert(2,'second')     #插入
print(li)
if 'liwj' in li:print('in')   #in
print(len(li))     #长度
# 模拟队列
l=[]
l.append('first')
l.append('second')
l.append('third')
print(l)
l.pop(0)
print(l)
l.pop(0)
l.pop(0)
# 模拟堆栈
l=[]
l.insert(0,'first')
l.insert(0,'second')
l.insert(0,'third')
print(l)
l.pop(0)
print(l)
l.pop(0)
l.pop(0)
# 列表li的其他操作
print(li.index('liwj'))   #列出'liwj'所在位置信息,不存在则报错
print(li.count('liwj'))   #计数
# print(li.sort())           #排序,仅针对数字
# print(li.sort(reverse=True))
print(li.remove('han'))   #删除
li.extend([1,2,4])        #扩展列表
print(li)
#字符其他需要了解的方法
name='egon hello'
print(name.find('o'))
print(name.find('x')) #若不存在不会报错,显示-1
print(name.find('o',3,6))
print(name.index('o'))
print(name.index('x')) #若不存在会报错
#count计数
print(name.count('o',1,3))
l=['egon','say','hello','world'] #类别内容必须都是字符串,相同类型也不行
l1=[1,2,3]
print(':'.join(l))
print(':'.join(l1)) #会报错
37:54

 元组tuple:

元组的元素可以使任何数据类型

元组的特性是:不可变(id/type/value不可变)

tu=('a','b',1,2,'gh')
print(tu[3])     #取值
print(tu[1:7:2]) #切片
print(len(tu))   #长度
print(tu.count('gh'))    #计数
print(tu.index('b'))     #索引到位置信息
if 'a' in tu:print('in') #in
print(tu)

字典dict:

注:key必须是不可变类型,或者说是可hash类型

取值,字典是无序的。

d={'name':'liwj','age':17,'Hobbies':'too many'}
# 字典常用操作
print(d['name'])     #取值
d['age']=18          #修改值
d.pop('Hobbies')     #删除 取到的是key
print(d.get('jkagl'))    #存在则列出位置信息,不存在为none
# 字典其他操作
print(d.keys(),d.values())    #列出所有的key和values
print(d.items())         #items中key和value都有
for item in d.items():
    print(item)
for key,value in d.items():
    print(key,value)
print(d.popitem())   #取到的是key:value,
print(d.fromkeys(['height','age','others'],20))  #字典其他创建方法
dic=dict(a=1,b=2)
print(dic)
d.update(dic)       #将dic字典信息更新到d字典中,有则改之,无则加之
d.setdefault('others',[]).append('play1')
print(d)

集合set:

 作用:去重和关系运算

注:1、集合中可以有多个元素,但每个元素都必须是不可变类型,即可hash类型。

  2、集合内的元素是唯一的,具有去重性。

  3、集合是无序的

s={1,'a','a',2,1}   #set
print(s)            #{1, 2, 'a'}
s1=set('hello')     #set另一种定义方式
print(s1)   #{'o', 'e', 'h', 'l'} 无序和去重
#关系运算
s2={1,10,11,23}
s3={1,11,33}
print(s2&s3)        #交集 {1, 11}
print(s2.intersection(s3))  #交集内置方法,后面一样
print(s2|s3)        #并集 {1, 33, 10, 11, 23}
s2.union(s3)
print(s2-s3)        #差集 {10, 23}
s2.difference(s3)
print(s3-s2)
print(s2^s3)        #对称差集 {33, 23, 10}
s2.symmetric_difference(s3)
s4={1,11}
print(s3 >= s4)     #s3为父集,s4为子集 True
#set其他操作
s.add(45) #增加
s.pop() #随机删除
s.remove(2) #删除具体值,若不存在报错
s.discard('vvv') #删除具体值,如不存在不会报错
print(s)

2、字符编码

3、文件处理

f=open('a.txt','r',encoding='utf-8')     #a.txt需要先建立或存在。默认是r读,可指定encoding格式
res=f.read() #读全部内容
print(res)
print(f.readline(),end='') #读一行
print(f.readlines()) #读全部行为列表

f.close() #一定记得关闭
del f #删除的是变量名称

with open('a.txt','w',encoding='utf-8') as f:   #不需要手动关闭f.close(),会自动关闭文件
#以下操作会覆盖文件中原来的内容
f.write('11111 ') #写
f.write('3333 44444 ') #写多行
f.writelines(['a ','c ','d ']) #列表写多行
#将a.txt中指定字符串替换成其他字符串写入b.txt文件中
with open('b.txt','w',encoding='utf-8') as write_f,
open('a.txt','r',encoding='utf-8') as read_f: #不需要手动关闭f.close(),会自动关闭文件
for line in read_f:
if 'SB' in line:
line=line.replace('SB','alex')
write_f.write(line)
else:
write_f.write(line)
with open('a.txt','r',encoding='utf-8') as read_f,
open('b.txt','w',encoding='utf-8') as write_f: #不需要手动关闭f.close(),会自动关闭文件
msg=read_f.read()
msg=msg.replace('SB','alex')
write_f.write(msg)
import os
os.remove('a.txt') #os层面删除a.txt,文件不存在则报错,
os.rename('b.txt','c.txt')#os层面更改文件名字,文件不存在则报错,
 
 

 
 
原文地址:https://www.cnblogs.com/liweijing/p/7144998.html