基本数据类型及内置方法
1.字符串的内置方法
1.类型转换
字符串可以把任意的其他类型都转成字符串
res=str({'a':1})
print(res,type(res)) #把字典转换成字符串类型
2.内置方法
2.1 索引
按索引取值,只能取,不能改
msg='hello world!'
print(msg[0]) # h 正向取
print(msg[-1]) # ! 反向取
2.2 切片
就是一个大字符串拷贝出一个子字符串
msg='hello world!'
res=msg[0:5] # 顾头不顾尾,索引是0到4
red=msg[0:8:2] # hlow
'''
[start:end:step] 0是开始 ,到8结束,2是索引加2,每隔两个取
msg[5:0:-1]反向取 # olle
'''
2.3 len()
len就是计算字符串的长度
msg='hello world!'
print(len(msg)) # 12
2.4 成员运算
成员运算in和not in
判断一个子字符串是否存在于一个大字符串中
print("alex" in "alex is sb")
print("alex" not in "alex is sb")
print(not "alex" in "alex is sb") # 不推荐使用
2.5 strip
移除字符串左右两侧的符号strip
msg='***hello world!***'
res=msg.strip('*') # 如果里面没有值默认的是去两边的空格部分,如果中间有*或空格不去 除
print(res) # hello world!
补充:lstrip(去左边的*或空格),rstrip(去右边的*或空格)
2.6 split
把一个字符串按照某种分隔符进行切分,得到一个列表
info='egon:18:male' #如果':'是空格,split()默认分隔符是空格
res=info.split(':')
print(res) # ['egon', '18', 'male']
补充:print(info.split(':',1)) # ["egon","18:male"] #分隔第一个
print(info.rsplit(':',1)) # ["egon:18","male"] #分隔最后一个
2.7 join
用于将序列中的元素以指定的字符连接生成一个新的字符串
s1 = "-"
s2 = ""
seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
print (s1.join( seq )) # r-u-n-o-o-b
print (s2.join( seq )) # runoob
2.8 replace
把字符串中的 old(旧字符串) 替换成 new(新字符串)
msg="you can you up no can no bb"
print(msg.replace("you","YOU",))
print(msg.replace("you","YOU",1)) # 如果指定第三个参数max,则替换不超过 max次。
2.9 isdigit
判断字符串是否由纯数字组成
print('123'.isdigit()) #ture
2.10 find and index的区别
find:如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。
index:方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常
语法:str.index(str, beg=0, end=len(string))
msg='hello egon hahaha'
print(msg.find('egon'))
print(msg.index('e'))
2.11 了解
折叠代码块
1、find,rfind,index,rindex,count msg='hello egon hahaha' 找到返回起始索引 print(msg.find('e')) # 返回要查找的字符串在大字符串中的起始索引 print(msg.find('egon')) print(msg.index('e')) print(msg.index('egon')) 找不到 print(msg.find('xxx')) # 返回-1,代表找不到 print(msg.index('xxx')) # 抛出异常 msg='hello egon hahaha egon、 egon' print(msg.count('egon'))2、center,ljust,rjust,zfill
print('egon'.center(50,''))
print('egon'.ljust(50,''))
print('egon'.rjust(50,'*'))
print('egon'.zfill(10))3、expandtabs
msg='hello\tworld'
print(msg.expandtabs(2)) # 设置制表符代表的空格数为24、captalize,swapcase,title
print("hello world egon".capitalize())
print("Hello WorLd EGon".swapcase())
print("hello world egon".title())5、is数字系列
.6、is其他
print('abc'.islower())
print('ABC'.isupper())
print('Hello World'.istitle())
print('123123aadsf'.isalnum()) # 字符串由字母或数字组成结果为True
print('ad'.isalpha()) # 字符串由由字母组成结果为True
print(' '.isspace()) # 字符串由空格组成结果为True
print('print'.isidentifier())
print('age_of_egon'.isidentifier())
print('1age_of_egon'.isidentifier())num1=b'4' #bytes
num2=u'4' #unicode,python3中无需加u就是unicode
num3='四' #中文数字
num4='Ⅳ' #罗马数字isdigit只能识别:num1、num2
print(num1.isdigit()) # True
print(num2.isdigit()) # True
print(num3.isdigit()) # False
print(num4.isdigit()) # Falseisnumberic可以识别:num2、num3、num4
print(num2.isnumeric()) # True
print(num3.isnumeric()) # True
print(num4.isnumeric()) # Trueisdecimal只能识别:num2
print(num2.isdecimal()) # True
print(num3.isdecimal()) # False
print(num4.isdecimal()) # False
4.4 添加值
append, insert,extend三种
l=[1,'c','b','a']
l.append(0) #按索引
print(l)
l.insert(0,'al') #指定索引位置添加
print(l)
l.extend('abc') #列表末尾一次性追加另一个序列中的多个值
print(l)
'''
[1, 'c', 'b', 'a', 0]
['al', 1, 'c', 'b', 'a', 0]
['al', 1, 'c', 'b', 'a', 0, 'a', 'b', 'c']
'''
4.5 删除操作
del ,pop ,remove
l=[111,'ccc','bb','aa']
del l[0] # 通用的删除方法,且没有返回值,索引不能进行赋值操作
print(l)
l.pop(0) # 根据索引删除的,不传索引,默认删除最后一个
print(l)
l.remove('bb') # 按指定元素删除
print(l)
'''
['ccc', 'bb', 'aa']
['bb', 'aa']
['aa']
'''
4.6 了解的内置方法
index() 查找指定元素
clear()清除list
reverse():不是排序,就是将列表倒过来 ,反转list
count() 统计元素出现的个数
sort ()排序 升序
3.元组及内置方法
1.作用
一个不可变的列表"
作用:按照索引/位置存放多个值,只用于读不用于改
2. 定义
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可
3. 类型转换
print(tuple('hello'))
print(tuple([1,2,3]))
print(tuple({'a1':111,'a2':333}))
4.内置方法
因为元组只能取不能改。所以内置方法少
4.1 按索引取值()
正向取,反向取
t=('aa','bbb','cc')
print(t[0])
4.2 切片(顾头不顾尾,步长)
t=('aa','bbb','cc','dd','eee')
print(t[0:3])
print(t[::-1])
4.3 长度
len()计算元组的长度
4.4 循环
for x in t:
print(x)
字典
3.1 作用
字典是另一种可变容器模型,且可存储任意类型对象
3.2 定义
{}内用逗号分隔开多个key:value,其中value可以使任意类型,但是key必须是不可变类型,且不能重复
3.3 造字典
方式一:
d=dict(x=1,y=2,z=3)
print(d)
方式二
info=[
['name','egon'],
('age',18),
['gender','male']
]
res=dict(info)
print(res)
'''
{'name': 'egon', 'age': 18, 'gender': 'male'}
'''
方式三:
keys=['name','age','gender']
d={}.fromkeys(keys,None)
print(d)
'''
{'name': None, 'age': None, 'gender': None}
'''
4 内置方法
4.1按key存取值
按key存取值,可存可取,但是针对赋值key存在则修改,不存在,则创建新值
4.2长度
len是计算key,key有多少,len就多长
4.3 删除操作
del ,pop, popitem
a={'k1':111,'k2':222,'k3':333}
del a['k1']
print(a)
res=a.pop('k2') # 根据key删除元素,返回删除key对应的那个value值
print(res)
res1 = a.popitem() # 随机删除,返回元组(删除的key,删除的value)
print(res1)
'''
{'k2': 222, 'k3': 333}
222
('k3', 333)
'''
# 键keys(),值values(),键值对items() =>在python3中得到的是老母鸡 不占内存空间
4.4了解
items:以列表返回可遍历的(键, 值) 元组数组
keys:返回一个迭代器,可以使用 list() 来转换为列表
values:返回一个迭代器,可以使用 list() 来转换为列表
setdefault:如果key有则不添加,返回字典中key对应的值,如果key没有则添加,返回字典中key对应的值
b={'a1':'bbb','a2':'ccc','a3':'ddd'}
b.setdefault('name','enum')
print(b)
'''
{'a1': 'bbb', 'a2': 'ccc', 'a3': 'ddd', 'name': 'enum'}
'''
update:更新
d={'k1':111}
d.update({'k2':222,'k3':333,'k1':1})
print(d)
'''
{'k1': 1, 'k2': 222, 'k3': 333}
'''
get
{'k1': 1, 'k2': 222, 'k3': 333}
print(d['k2']) # key不存在则报错
print(d.get('k1')) # 1
print(d.get('k4')) # key不存在不报错,返回None
4. 集合:
1.定义:
1:每个元素必须是不可变类型
2:集合内没有重复的元素
3:集合内元素无序
2.使用:关系运算:
friends1={'zc','bc','ac','bb'}
friends2={'zc','bb','cc','lk'}
res=friends1|friends2
print(res)
交集
res=friends1&friends2
print(res)
差集
res=friends1-friends2
print(res)
对称集
res=friends1^friends2
print(res)
判断值
res=friends2==friends1
rint(res)
去重
l=[
{'name':'lili','age':18,'sex':'male'},
{'name':'jack','age':73,'sex':'male'},
{'name':'tom','age':20,'sex':'female'},
{'name':'lili','age':18,'sex':'male'},
{'name':'lili','age':18,'sex':'male'},
]
dic=[]
for i in l:
if i not in dic:
dic.append(i)
print(dic)
3.其他的内置方法
s={1,2,3}
需要掌握的内置方法1:discard
s.discard(4) # 删除元素不存在do nothing
print(s)
s.remove(4) # 删除元素不存在则报错
需要掌握的内置方法2:update
s.update({1,3,5})
print(s)
需要掌握的内置方法3:pop
res=s.pop()
print(res)
需要掌握的内置方法4:add
s.add(4)
print(s)
其余方法全为了解
res=s.isdisjoint({3,4,5,6}) # 两个集合完全独立、没有共同部分,返回True
print(res)
了解
s.difference_update({3,4,5}) # s=s.difference({3,4,5})
print(s)

浙公网安备 33010602011771号