python第二周数据类型 字符编码 文件处理

第一数据类型需要学习的几个点:

用途

定义方式

常用操作和内置的方法

该类型总结:

可以存一个值或者多个值

只能存储一个值

可以存储多个值,值都可以是什么类型

有序或者无序

可变或者不可变

二:数字整数与浮点

age=10

浮点类型

salary=float(300.3)

salary=300.03 print(salary)

salary=300.03  
print(salary) 长整形(了解)
    在python2中(python3中没有长整形的概念):      
    >>> num=2L
    >>> type(num)
    <type 'long'> #复数(了解)  
    >>> x=1-2j
    >>> x.real
    1.0
    >>> x.imag
    -2.0   第三 字符串的用法 name='egon' 优先掌握的操作:
1.字符串按照索引取值,正向取值反向取值,步长,反向取值步长2.字符串切片
print(aa[-5:])  取倒数5个数
 
name='hello word'
#字符串从0开始
print(name[])
#字符串0到5
print(name[:])
#倒数第二个,反着取数
print(name[-]) #第五个是空格,反着取步长是1,负号代表反着取值,
# oll 顾头不顾尾
print(name[::-])
附加说明:字符串取得值是新获取的值新的内存空间,原来的字符串没有改变

3.长度字符串长度
print(len(name))
10 4.成员运算in和not in
print('hello' in  name)
print('hello' not in name)
print('eeee' not in name)
True
False
True
第五移除空白
name='  egon  '

print(name.strip())
print(name.lstrip())
print(name.rstrip()) name2='**egon**' print(name2.strip('*'))
print(name2.lstrip('*'))
print(name2.rstrip('*')) egon
egon 
  egon
egon
egon**
**egon
6.切分split
name='jenkins:x:997:995:Jenkins Automation Server:/var/lib/jenkins:/bin/false'

cc=name.split(':')

print(cc)
print(cc[0]) print(name) ['jenkins', 'x', '', '', 'Jenkins Automation Server', '/var/lib/jenkins', '/bin/false']
jenkins
jenkins:x:997:995:Jenkins Automation Server:/var/lib/jenkins:/bin/false

循环

name='jenkins:x:997:995:Jenkins Automation Server:/var/lib/jenkins:/bin/false'

print(list(name))
['j', 'e', 'n' .....] 放入了类表中
for i in name
  print i
切片:第二个参数1表示切得次数
file_path='C:\\a\\d.txt'
print(file_path.split('\\',1))
#['C:', 'a\\d.txt']
print(file_path.split('\\'))
#['C:', 'a', 'd.txt'] 循环
只有0的时候才能省略开始的位置range(0,10,2) range(10) for i in range(0,10,2):
print(i) for i in range(10):
print(i) name='hello word' for i in range(len(name)):
print(name[i]) 第二掌握的
#1、strip,lstrip,rstrip
# print("**alex****".strip('*'))
# print("**alex****".lstrip('*'))
# print("**alex****".rstrip('*')) #2、lower,upper
# print('ALeX'.lower())
# print('aaa'.upper()) 3.startswith,endswith name='hello word' print(name.startswith('h'))
print(name.startswith('hello'))
print(name.endswith('d')) 4.format的三种用法
print('my name is %s age is %s ttt' %('egon',18)) print('my name is {} age is {}'.format('egon',18)) print('my{0} name is {1} age {1} i {0} s {1}'.format('egon',18)) print('my{name} name is {pp} age'.format(pp=18,name='egon')) 5.split和join info='root:x:0:0'
l=info.split(':')
print(l) print(':'.join(l))
print(''.join(l)) 6.replace 替换和全部替换. info='root:x:0:0' print(info.replace(':','==',2))
print(info.replace(':','==')) 7.isgigit
aa=''
print(aa.isdigit()) aa=55
print(aa.isdigit())
#AttributeError: 'int' object has no attribute 'isdigit' 下面的报错init 不能用这个方法,只有字符串才行

#1、find,rfind, 

index,rindex,  查找字符串对应的索引数字

count  统计字符串出现的次数

aa='tt  hello word hello wordhello word'

print(aa.index('h'))

name='egon say hello'
print(name.find('o',1,3)) #顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引
print(name.find('o')) #顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引 #2、center,ljust,rjust,zfill 对齐填充字符
#3、expandtabs 修改tab键默认的空格为指定的空格,修改4个空格为多个
#4、captalize,swapcase,title 大写首字母或者单词
#5、is数字系列 是否数字 ,罗马数字和汉字数字是否数字
#6、is其他 #1、strip,lstrip,rstrip
#2、lower,upper
#3、startswith,endswith
#4、format的三种玩法
#5、split,rsplit
#6、join
#7、replace
#8、isdigit 复制代码 复制代码
#strip
name='*egon**'
print(name.strip('*'))
print(name.lstrip('*'))
print(name.rstrip('*')) #lower,upper
name='egon'
print(name.lower())
print(name.upper()) #startswith,endswith
name='alex_SB'
print(name.endswith('SB'))
print(name.startswith('alex')) #format的三种玩法
res='{} {} {}'.format('egon',18,'male')
res='{1} {0} {1}'.format('egon',18,'male')
res='{name} {age} {sex}'.format(sex='male',name='egon',age=18) #split
name='root:x:0:0::/root:/bin/bash'
print(name.split(':')) #默认分隔符为空格
name='C:/a/b/c/d.txt' #只想拿到*目录
print(name.split('/',1)) name='a|b|c'
print(name.rsplit('|',1)) #从右开始切分 #join
tag=' '
print(tag.join(['egon','say','hello','world'])) #可迭代对象必须都是字符串 #replace
name='alex say :i have one tesla,my name is alex'
print(name.replace('alex','SB',1)) #isdigit:可以判断bytes和unicode类型,是最常用的用于于判断字符是否为"数字"的方法
age=input('>>: ')
print(age.isdigit()) 复制代码  其他操作(了解即可) #1、find,rfind,index,rindex,count
#2、center,ljust,rjust,zfill
#3、expandtabs
#4、captalize,swapcase,title
#5、is数字系列
#6、is其他 复制代码
#find,rfind,index,rindex,count
name='egon say hello'
print(name.find('o',1,3)) #顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引
# print(name.index('e',2,4)) #同上,但是找不到会报错
print(name.count('e',1,3)) #顾头不顾尾,如果不指定范围则查找所有 #center,ljust,rjust,zfill
name='egon'
print(name.center(30,'-'))
print(name.ljust(30,'*'))
print(name.rjust(30,'*'))
print(name.zfill(50)) #用0填充 #expandtabs
name='egon\thello'
print(name)
print(name.expandtabs(1)) #captalize,swapcase,title
print(name.capitalize()) #首字母大写
print(name.swapcase()) #大小写翻转
msg='egon say hi'
print(msg.title()) #每个单词的首字母大写 #is数字系列
#在python3中
num1=b'' #bytes
num2=u'' #unicode,python3中无需加u就是unicode
num3='四' #中文数字
num4='Ⅳ' #罗马数字 #isdigt:bytes,unicode
print(num1.isdigit()) #True
print(num2.isdigit()) #True
print(num3.isdigit()) #False
print(num4.isdigit()) #False #isdecimal:uncicode
#bytes类型无isdecimal方法
print(num2.isdecimal()) #True
print(num3.isdecimal()) #False
print(num4.isdecimal()) #False #isnumberic:unicode,中文数字,罗马数字
#bytes类型无isnumberic方法
print(num2.isnumeric()) #True
print(num3.isnumeric()) #True
print(num4.isnumeric()) #True #三者不能判断浮点数
num5='4.3'
print(num5.isdigit())
print(num5.isdecimal())
print(num5.isnumeric())
'''
总结:
最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景
如果要判断中文数字或罗马数字,则需要用到isnumeric
''' #is其他
print('===>')
name='egon123'
print(name.isalnum()) #字符串由字母或数字组成
print(name.isalpha()) #字符串只由字母组成 print(name.isidentifier())
print(name.islower())
print(name.isupper())
print(name.isspace())
print(name.istitle()) 复制代码
第四: 列表:

#优先掌握的操作:
#1、按索引存取值(正向存取+反向存取):即可存也可以取
name=['aa','bb','cc'] print(name[0])
print(name[-2:]) #取倒数两个值
print(name[:-1]) #取除了最后一个值剩下的值,或者说所有值除了最后一个
name[1]='xx'
print(name)
#2、切片(顾头不顾尾,步长)
print(name[1:3])
#3、长度
print(len(name))
#4、成员运算in和not in
print('aa' in name)
print('aa' not in name)
#5、追加
name=['aa','bb','cc','dd','ee']
print(name.append('tt'))
print(name)
['aa', 'bb', 'cc', 'dd', 'ee', 'tt']
#6、删除
name=['aa','bb','cc','dd','ee']
vl=name.pop() # pop的删除值还可以获取到删除的值,默认从右到左删除
#name.remove('tt') #remove单纯删除
vl=name.pop(2) #cc 指定了值就是制定索引值从左到右
print(vl)
print(name)
结果
# ['aa', 'bb', 'cc', 'dd'] name=['aa','bb','cc','dd','ee']
name.insert(1,'') #在索引1的位置插入值,或者说在一之前插入值
# name.clear() #清空整个列表
print(name) name=['aa','bb','cc','dd','ee']
name.insert(1,'') #在索引1的位置插入值,或者说在一之前插入值
# name.clear() #清空整个列表
name.reverse() #反过来显示
print(name) #下面是显示索引号
# my_girl_friends=['alex','wupeiqi','yuanhao','yuanhao',4,5]
# print(my_girl_friends.index('wupeiqi'))
# print(my_girl_friends.index('wupeiqissssss')) #反转排序 # l=[1,10,4,11,2,]
# l.sort(reverse=True)
# print(l)
l.sort(reverse=True) l=['egon','alex','wupei']
l.sort()
print(l)
#首字母排序
#['alex', 'egon', 'wupei'] #7、循环
# my_girl_friends=['alex','wupeiqi','yuanhao',4,5] # i=0
# while i < len(my_girl_friends):
# print(my_girl_friends[i])
# i+=1 # for item in my_girl_friends:
# print(item) # for i in range(10):
# if i== 3:
# break
# # continue
# print(i)
# else:
# print('===>')
元组:元组和列表相似,但是元组是不可变类型(不可变类型可以当做字典的key).如果用于只读可以使用元组

aa=(11,22,33,44,55)

print(type(aa))

#元组里面可以存放列表,列表里面的元素可以修改,但是列表整体不能修改替换为别的值
t=(1,2,['a','b'])
print(id(t[2]))
t[2][0]='A'
print(id(t[2]))
print(t) age=(11,22,33,44,55) print(type(age)) print(age.index(33))
#print(age.index(33333)) #不存在的索引报错 print(age.count(3333)) ============ msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
} for i in msg_dic:
print('可购买的商品:', i, '个数', msg_dic[i])
goods=[]
while True:
sp = input("输入买的商品:")
if sp not in msg_dic:
print('输入的商品不存在.')
continue
while True:
gs=input("输入买的个数:")
if not gs.isdigit():
print('输入的个数不是数字')
continue
break
goods.append((sp,gs)) print(goods)
============================
字典:
#作用:存多个值,key-value存取,取值速度快 #定义:key必须是不可变类型,value可以是任意类型
info={'name':'egon','age':18,'sex':'male'} #本质info=dict({....})

info=dict(name='egon',age=18,sex='male')

info=dict([['name','egon'],('age',18)])

{}.fromkeys(('name','age','sex'),None) #优先掌握的操作:
#1、按key存取值:可存可取
print(info['sex'])
取值:
for i in info:
print(i)
设置值: dict.setdefault(key,defvalue) #设置一个默认值,如果有这个值就用原来的值,如果没有就使用新的复制
info={'name':'egon','age':18,'sex':'male'} info.setdefault('tt',66)
info.setdefault('name','erdan') print(info) #{'name': 'egon', 'age': 18, 'sex': 'male', 'tt': 66} #2、长度len info={'name':'egon','age':18,'sex':'male'}
print(len(info))
3 #3、成员运算in和not in 根据key来说
info={'name':'egon','age':18,'sex':'male'} print(len(info)) print('name' in info)
print('egon' in info) #4、删除
info={'name':'egon','age':18,'sex':'male'} print(info.pop('name')) print(info)
#删除后键值一起删除,pop删除可以获取删除的值
egon
{'age': 18, 'sex': 'male'} #5、键keys(),值values(),键值对items()
info={'name':'egon','age':18,'sex':'male'} print(list(info.items())[0])
('name', 'egon') #6、循环 ======================
集合:集合是为了处理两个集合之间的关系,单纯取出单个值无意义. 集合无序的,集合是不能重复的可以充当去重功能.
交集并集合集 用:去重,关系运算, #定义:
知识点回顾
可变类型是不可hash类型
不可变类型是可hash类型 #定义集合:
集合:可以包含多个元素,用逗号分割,
集合的元素遵循三个原则:
1:每个元素必须是不可变类型(可hash,可作为字典的key)
2:没有重复的元素
3:无序 注意集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值 #优先掌握的操作:
#1、长度len
#2、成员运算in和not in #3、|合集
#4、&交集
#5、-差集
#6、^对称差集
#7、==
#8、父集:>,>=
#9、子集:<,<=
上一篇:(转)解决类似 /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found 的问题


下一篇:Apache2.4.x与Apache2.2.x的一些区别