python数据类型

1、数值类型包括整型、浮点型、复数

整型:int
浮点型:float
复数:a+bj complex
type()获取变量的类型
例:
a=100
b=5.2
c=3+4j
d=complex(3,4)#复数的两种表示形式
print(a,type(a))
print(b,type(b))
print(c,type©)
print(d,type(d))
在这里插入图片描述
科学计数法:
a=3.1415926e3
b=3.1415926e-3
print(a)
print(b)
执行结果为:3141.5926和0.0031415926

2、特殊类型

布尔类型(布尔类型只有两个值True和False)、空(只有一个None)
x=True
print(x,type(x))
y=None
print(y)
执行结果为:True和None

3、文本类型

字符串str,字节串bytes
s1=‘helloworld’
s2=“helloworld”
s3=’’‘helloworld’’’
s4=""“helloworld”""#以上方式都可以定义字符串
print(s1)
print(s2)
print(s3)
print(s4)
其中’’’ ‘’‘和""" “”"中间可以使用enter键换行,而’ ‘和" "不能使用enter,如果使用enter会自动在中间加“\”来连接
s1=‘hello’
‘world’
s2=“hello”
“world”
s3=’’‘hello
world’’’
s4=""“hello
world”""
print(s1)
print(s2)
print(s3)
print(s4)
执行结果为:
helloworld
helloworld
hello
world
hello
world

其中“\”可以让特殊字符变成普通字符
s=hello\nworld
print(s)
结果为:hello\nworld

r是原始字符,在r后面的字符都是原始字符
s5=r’hello\nworld’
print(s5)
结果为:hello\nworld

#字节串:bytes
b1=b’helloworld’
print(b1,type(b1))
#编码:字符串转换为字节串
b2=‘helloworld’.encode(‘utf-8’)
print(‘b2=’,b2,type(b2))
#解码:字节串转换为字符串
b3=b2.decode(‘utf-8’)
print(b3,type(b3))
执行结果:
b’helloworld’ <class ‘bytes’>
b2= b’helloworld’ <class ‘bytes’>
helloworld <class ‘str’>
注:如果没有编码就解码会出现错误

4、容器类型

列表、元组、字典、集合
#列表:list,元素可以改变且元素可以是不同的类型
lt=[1,2,3,‘a’,‘b’,‘c’]
print(lt,type(lt))
#通过下标访问元素,从左到右从0开始,从右到左从-1开始
print(lt[0],lt[5])
#列表不能越界,如果越界会出现IndexError: list index out of range的错误
print(lt[9])

#元组:tuple,元素不能改变,可以增加和删除里面的元素
tp=(1,2,3)
print(tp,type(tp))
#如果元组中只有一个元素时,末尾要加一个逗号
tp2=(100,)
print(tp2,type(tp2))

#集合:set,元素是无序的且不能重复
s={1,2,3,6,8}
s1={2,6,7,8,4}
print(s,type(s))
print(s&s1)#交集
print(s|s1)#并集
#差集
print(s-s1)#在s中不在s1中
print(s1-s)#在s1中不在s中
#空集合不能用{}定义,用其定义的是一个空子典
s3={}
s4=set()#定义空子典
print(s3,type(s3))
print(s4,type(s4))

#字典:dict,可变类型
d1={‘name’:‘张三’,‘age’:18,}
print(d1,type(d1))
#字典根据键来访问值,如果访问的键不存在会报keyerror的错误
print(d1[‘age’])
print(d1.get(‘school’))#若存在就返回对应的值,如果不存在键默认返回None
print(d1.get(‘school’,‘school’))#不存在所查的键时,第二个是指定的返回值

**#len()**统计元素个数
print(len(s1))
print(len(d1))
print(len(s))

#数值类型转换
a=float(int(input(‘输入数字’)))
print(a,type(a))
#容器类型转换,数值类型不能转换成容器类型

a=list(‘hello’)
b=set((1,2,3))
c=list({4,8,9})
d=list({‘name’: ‘dahua’, ‘age’: 18})
print(a,type(a))
print(b,type(b))
print(c,type©)
print(d,type(d))#字典转换成列表时,只显示键
#字典转换成其他形式的容器时需要特殊的格式
d=[(‘name’,‘zhangsan’),(‘age’,18)]
print(d,type(d))
f=dict(d)#转换成字典
print(f,type(f))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值