python数据类型及使用方法_Python的数据类型和常用方法大全

本文详细介绍了Python的基础数据类型,包括数字、字符串、列表、元组、字典和集合的操作,如取值、切片、成员运算、格式化输出、字符串处理、列表动态操作、元组的索引、字典的增删查改以及集合的运算。此外,还展示了如何使用这些数据结构进行简单的购物车功能实现。通过实例演示了各种操作方法,帮助读者掌握Python编程中的基本数据结构和操作技巧。
摘要由CSDN通过智能技术生成

数据类型

一.数字

整形int

x=10 #x=int(10)

print(id(x),type(x),x)

浮点型float

salary=3.1 #salary=float(3.1)

print(id(salary),type(salary),salary)

二.字符串

name='hantao'

#按索引取值(正向取+反向取) :只能取

print(name[0],type(name[0]))print((name[-1]))

#切片(顾头不顾尾,步长)

print(name[1:3])print(name[0:5:2])print(name[5::-1])

#长度len

print(len(name))

#成员运算in和not in

msg='hellochantao'

print('hantao'in msg)

#移除空白strip

passwd='hantao123'

print(passwd.strip())

passwd1='****hantao***'

print(passwd1.strip('*'))

print(passwd.lstrip())

print(passwd.rstrip())

#切分split

user='hantao:liangchaowei:liudehua'

print(user.split(':'))

user.split('',1) #选定切分的数量

user.rsplit('',1) #从右侧切分

#判断开头结尾

msg='hantao_is_cool'

print(msg.startswith('han'))print(msg.endswith('cool'))

#用replace替换

msg='hantao say i have a tesla,my name is hantao'

print(msg.replace('hantao','sb',1)) #替换,后面数字是替换数量

#format格式化

print('my name is %s,my age is %s'%('hantao',18))print('my name is {},my age is {}'.format('hantao',18))print('my name is {0},my age is {1}'.format('hantao',18))print('my name is {a},my age is {b}'.format(a='hantao',b=18))

#查找

msg='hello world'

print(msg.find('hel'))print(msg.index('o'))print(msg.count('l',0,4))

#join连接

print(':'.join(['hantao', 'liangchaowei', 'liudehua'])) #必须是字符串放在一个列表中传入join

#填充

print('info'.center(30,'='))print('info'.rjust(30,'='))print('info'.ljust(30,'='))print('info'.zfill(30))

#is数字系列

#在python3中

num1=b'4' #bytes

num2=u'4' #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

'''

#find,rfind,index,rindex,count

name='hantao say hello'

print(name.find('h',1,3)) #顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引#print(name.index('h',2,4)) #同上,但是找不到会报错

print(name.count('h',1,3)) #顾头不顾尾,如果不指定范围则查找所有

#center,ljust,rjust,zfill

name='hantao'

print(name.center(30,'-'))print(name.ljust(30,'*'))print(name.rjust(30,'*'))print(name.zfill(50)) #用0填充

#expandtabs 方法把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8。

name='egon\thello'

print(name)print(name.expandtabs(1))

#captalize,swapcase,title

print(name.capitalize()) #首字母大写

print(name.swapcase()) #大小写翻转

print(msg.title()) #每个单词的首字母大写

#is其他

print('===>')

name='hantao123'

print(name.isalnum()) #字符串由字母或数字组成

print(name.isalpha()) #字符串只由字母组成

print(name.isidentifier())print(name.islower())print(name.isupper())print(name.isspace())print(name.istitle())

四.列表

#按索引存取值(正向存取+反向存取):即可存也可以取

print(my_familly[2])print(my_familly[-1])

#切片(顾头不顾尾,步长)

print(my_familly[0:3])print(my_familly[0:5:2])print(my_familly[5::-1])

#长度

print(len(my_familly))

#成员运算in和not in

print('nep'in my_familly)

#追加

my_familly.append('Corgi')print(my_familly)

#删除

goods=['apple','banana','pear']del goods[-1]print(goods.remove('apple')) #不返回删除值

print(goods.pop(1)) #按照索引删,默认末尾开始删,返回删除值

print(goods)

#其他

goods=['apple','banana','pear','banana']#goods.insert(0,'sb') #具体插入的位置#goods.extend(['meat','eggs'])#print(goods.count('banana'))#goods.reverse() #反转#l=[2,4,6,1,-3]#l.sort(reverse=True)#print(l)

print(goods)

五.元祖

ages=(23,34,23,12)#按索引取值(正向取+反向取):只能取

print(ages[1])#切片(顾头不顾尾,步长)

print(ages[0:2])#长度

print(len(ages))#成员运算in和not in

print(23 in ages)

ages=(23,34,23,12)print(ages.index(12)) #查找索引

print(ages.count(23)) #查找个数

小练习

'''简单购物车,要求如下:

实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入'''msg_dic={'apple':10,'tesla':100000,'mac':3000,'lenovo':30000,'chicken':10,

}

l=[]whileTrue:for key inmsg_dic:print(key,msg_dic[key])

goods=input('input your good:').strip()if goods not in msg_dic:continue

whileTrue:

counts=input('input the number:').strip()if counts.isdigit():breakl.append((goods,msg_dic[goods],counts))print(l)

六.词典

info={'name':'egon','age':18,'sex':'male'}#按key存取值:可存可取

print(info['name'])

info['hobbies']=['eat','drink','sleep']print(info)#长度len

print(len(info))#删除

print(info.pop('na1me',None))#键keys(),值values(),键值对items()

print(info.keys())print(info.values())print(info.items())for item ininfo.items():print(item)

info={'name':'egon','age':18,'sex':'male'}print(info.get('name')) #取出value

print(info.get('na1me')) #返回None

print(info.popitem()) #随机删

t=['23','23','45','45']

a,*_,d=t #压缩赋值

print(a,d)for a,b ininfo.items():print(a,b)

info_new={'a':1,'b':3,'name':'hantao'}

info.update(info_new)#没有则新加,有则更新

print(info)

dic={}.fromkeys(['name','age','hobbies']) #初始字典

print(dic)print(info.setdefault('age','20')) #有则不改(且返回有的值),无则增

#字典推导式

d= {'A' : 1, 'B' : 2, 'C' : 3}

d_new={v:k for k,v in d.items()}

七.集合

'''1:每个元素必须是不可变类型(可hash,可作为字典的key)

2: 没有重复的元素

3:无序'''

#作用:去重,关系运算

s={1,2,'a'} #s=set({1,2,'a'})

s1={1,2,3}

s2={2,3,4}#| 并集

s1|s2

s1.union(s2)#& 交集

s1&s2

s1.intersection(s2)

s1.intersection_update(s2)#- 差集

s1-s2

s1.difference(s2)

s1.sifference_update(s2)#^ 对称差集

s1^s2

s1.symmetric_difference(s2)#父集

s1>=s2

s1.issuperset(s2)#子集

s1<=s2

s1.issubset(s2)

s1={1,2,3,4,'a'}#print(s1.pop()) #随机删,返回结果#print(s1.remove(1)) #删元素,不返回值,元素不存在,报错#s1.discard(1) #删元素,不返回值,元素不存在,不报错

s2={5,6}print(s1.isdisjoint(s2)) #s1和s2没有交集,则返回True

#有如下列表,列表元素为不可hash类型,去重,得到新列表,且新列表一定要保持列表原来的顺序

l=[

{'name':'egon','age':18,'sex':'male'},

{'name':'alex','age':73,'sex':'male'},

{'name':'egon','age':20,'sex':'female'},

{'name':'egon','age':18,'sex':'male'},

{'name':'egon','age':18,'sex':'male'},

]

l1=[]for i inl:if i not inl1:l1.append(i)print(l1)

#另一种集合的数据类型

s=forenset()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值