Python数据类型

一、数字类型

1.1 整型int基本使用
1.1.1 用途
年龄、等级、号码
1.1.3 定义方式
age = 18  # age=int(18)
1.1.4 数据类型转换
x = int("     103         ")  # 把纯数字组成的字符串转换成int类型
print(x, type(x))
1.1.5 常用操作+内置的方法
 + - * / % > >=
1.1.6 int总结
存一个值、不可变类型
1.2 浮点型float基本使用
1.2.1 用途:
薪资、医学、高精度仪器值
1.2.2 定义方式
salary = 3.3  # salary=float(3.3)
1.2.3 数据类型转换
x=float("  3.3    ")
print(x,type(x))
1.2.4 常用操作+内置的方法
+ - * / % > >=
1.2.5 float总结
存一个值、不可变类型
x = 3.1
print(id(x))
x = 3.3
print(id(x))
1.2.6 复数
x = 2 + 3j
print(x, type(x))
print(x.real)
print(x.imag)
1.3 进制
# 十进制:0-9
# 二进制:0-1
# 八进制:0-7
# 十六进制:0-9 a b c d e f

# 十进制<-二进制
# 1011
# 1*2^3 + 0*2^2 + 1*2^1 + 1*2^0
# 8     + 0     + 2     + 1 =》11

# 十进制<-八进制
# 1011
# 1*8^3 + 0*8^2 + 1*8^1 + 1*8^0

# 十进制<-十六进制
# 1011
# 1*16^3 + 0*16^2 + 1*16^1 + 1*16^0

二、字符串类型

2.1 用途
十分广泛
2.2 定义方式
msg="abc"  # msg=str("abc")
# 数据类型转换
res=str(1111)  # 可以把所有类型转换成字符串类型
print(res,type(res))
2.3 常用操作+内置的方法
2.3.1 按索引取值(正向取+反向取) :只能取
msg = "hello world"
print(msg[0])
# msg[0]="H"  # 不能改
print(msg[-1])
2.3.2 切片(顾头不顾尾、左闭右开)
print(msg[3:5])
print(msg[3:8])
print(msg[3:8:2])
print(msg[8:3:-1])  # 8 7 6 5 4
print(msg[:3])
print(msg[::])
print(msg[:])
print(msg[::2])
print(msg[10::-1])
print(msg[::-1])
2.3.3 长度len:统计的是字符个数
msg = "h e你"
print(len(msg))
2.3.4 成员运算in和not in
msg = "hello world"
print("he" in msg)
print("h" in msg)
# print(not 'egon' in msg)  # 不推荐
print('egon' not in msg)  # 推荐
2.3.5 移除空白strip
name = "           egon          "
print(name.strip())
print(name)

name = "** *eg*on***"
print(name.strip("*"))

x = "*(-)=+abc=-)*/"
print(x.strip("*()-=+/"))

name = input("username>>>: ").strip()
pwd = input("password>>>: ").strip()
if name == "egon" and pwd == "123":
    print("ok")
else:
    print('error')
2.3.6 切分split
info = "root:123:0:0"
res = info.split(":", 1)
print(res[0])
print(res)
2.3.7 循环
msg = "hello"
for i in msg:
    print(i)
2.4 字符串类型需要掌握的操作
#1、strip, lstrip, rstrip  去除左右字符(空格、符号等)
print("       xxx      ".strip())
print("*******xxx******".strip('*'))
print("       xxx      ".lstrip())
print("       xxx      ".rstrip())
# 2、lower, upper
print("HeLlo".upper())
print("HeLlo".lower())

# 3、startswith,endswith 判断是否以什么开头和结尾
print("wushu666".startswith('wu'))
print("wushu666".startswith('shu'))

# 4、format的三种玩法
print("My name is {xxx} and my age is {yyy}.".format(yyy=18, xxx="wu"))
print("My name is {} and my age is {}.".format(18, "wu"))
print("My name is {0}{0}{0} and my age is {1}{0}.".format(18, "wu"))

# format 高级玩法
# 对齐
print("My name is {0:*<10} and my age is {1:(<12}.".format(18, "wu"))
print("My name is {0:*>10} and my age is {1:(>12}.".format(18, "wu"))
print("My name is {0:*^10} and my age is {1:)^12}.".format(18, "wu"))
# 进制与精度
print("My name is {0:b} and my age is {1}.".format(18, "wu"))
print("My name is {0:o} and my age is {1}.".format(18, "wu"))
print("My name is {0:x} and my age is {1}.".format(18, "wu"))
print("My name is {0:,} and my age is {1}.".format(18381231803, "wu"))
print("My name is {0:.3f} and my age is {1}.".format(188.23132148, "wu"))
# f python新版本可以用
name = "wu"
age = 18
print(f"My name is {name} and my age is {age}.")
# 字典
info = {"name": "wu", "age": 18}
print("My name is {name} and my age is {age}.".format(**info))
# 列表
l = [111, 222]
print("My name is {} and my age is {}.".format(*l))

# 5、split,rsplit 分割(空格、字符等)
info = "root:a:c:b:11:31"
l1 = info.split(":")
print(l1)

# 6、join   连接
print(":".join(l1))

# 7、replace 替换

# 8、isdigit 判断字符串是否由纯数字组成
print('222'.isdigit())

age = input("your age:").strip()
if age.isdigit():
    age = int(age)
    if age > 18:
        print("too big")
    elif age < 18:
        print("too small")
    else:
        print("you got it")
else:
    print("必须输入数字!")
2.5 字符串类型需要了解的操作
# 1、 find,rfind, index, rindex, count
msg = "xxdswushu3214fwushusndkka"
print(msg.find("wushu"))
print(msg.rfind("wushu"))
print(msg.index("wushu"))
print(msg.rindex("wushu"))

# 2、center, ljust, rjust, zfill
print("wushu".center(30, "*"))
print("wushu".ljust(30, "*"))
print("wushu".rjust(30, "*"))
print("wushu".zfill(30))

# 3、expendtabs

# 4、captalize,swapcase,title
print("hello world".capitalize())
print("hello world".title())
print("hello world".swapcase())

# 5、is数字系列
num1 = b'4'  # bytes
num2 = u'4'  # unicode,python3中无需加u,就是unicode
num3 = '四'  # 中文数字
num4 = ''   # 罗马数字

bytes,unicode
print(num1.isdigit())
print(num2.isdigit())
print(num3.isdigit())
print(num4.isdigit())

unicode,中文,罗马
print(num2.isnumeric())
print(num3.isnumeric())

unicode
print(num2.isdecimal())
print(num3.isdecimal())
print(num4.isdecimal())

# 6、is其他
name = 'egon123'
print(name.isalnum())  # 字母或数字组成
print(name.isalpha())  # 只由字母组成
print(name.islower())
print(name.isupper())
name = "    1    "
print(name.isspace())
name = "Hello World"
print(name.istitle())
2.6 字符串类型总结
存一个值、有序、不可变
x = "hello"
x[0] = "H"

三、列表类型

3.1 用途
按照位置记录多个值,按照顺序取值
3.2 定义方式
[]内用逗号分开多个任意类型的值
l = [111, 222, 333, 'aaa', 'bbb']
print(l)
print(list("Hello world"))
print(list(range(5)))
3.3 常用操作+内置的方法
# 按索引取值
print(l[0])
print(l[-1])
print(id(l))
# 切片(左闭右开)
print(l[1:3])
# 长度
print(len(l))
# 成员运算 in 与 not in
print(222 in l)
# 追加
l.append("ccc")
print(l)
# 插入
l.insert(1, "uuu")
print(l)
# 删除
# 万能删除 del
del l[0]
# remove删除   指定元素删除
l.remove("uuu")
#pop删除   指定索引删除,会有返回值--删除的元素
l.pop(2)
#循环
3.4 列表类型需要掌握的操作
l = [111, 222, 333, 111, 444, 555, 666, 777]
print(l.count(111))
l.extend("hello")
l.reverse()
l = l[::-1]
print(l.index(222))
l.clear()
# 深浅拷贝:
res = l.copy()    # 浅拷贝 --可变类型的内存地址指向没有拷贝,只是指向这个可变类型的内存地址拷贝了
res = l[:]  # 浅拷贝
print(res)
# 深拷贝 -- 所有的内存地址指向都拷贝了,包括可变类型的内存地址指向。在源数据改变的时候,深拷贝的数据不会变
from copy import deepcopy
l2 = deepcopy(l)
print(l2)
3.5 列表类型总结
存多个值、有序、可变

四、元组类型

4.1 用途
按照位置记录多个值,按照顺序取值
4.2 定义方式
# ()内用逗号分开多个任意类型的值
t = (111, 333, 555, 'ggg', [333, 555])
t = (1,)
print(tuple('Hello'))
4.3 常用操作+内置的方法
与列表一样
4.4 需要掌握的
t = (111, 333, 555, 'ggg', [333, 555])
print(t.index(111))
print(t.count(333))
# 可以改元组内可变类型的值
4.5 元组类型总结
存多个值、有序、不可变

五、字典类型

5.1 用途
按照 key:value 的形式存放多个值
5.2 定义
在{ }内用逗号分开多个 key:value 元素,其中value可以是任意数据类型,而key必须是不可变类型,key不能重复
res1 = dict([('k1', 111), ('k2', 222), ('k3', 333)])
res2 = dict(x=111, y=222, z=333)
res3 = {}.fromkeys(["name", "age", "gender"], None)  # 快速造只有key的字典
print(res1, res2, res3)
res4 = {}
print(type(res4))
5.3 常用操作与内置方法
#1、 按key存取值:可存可取
d = {'k1': 111, 'k2': 222, 'k3': 333}
print(d['k1'])
print(d.keys())
d['k1'] = 666
d['k4'] = 444
print(d)
# 2、长度len
print(len(d))
# 3、成员运算in和not in
print('k1' in d)
# 4、删除
# del d['k1']
# print(d)
res = d.pop('k2')
print(res)
print(d)
# 5、键keys(),值values(),键值对items()
# 6、循环
for k, v in d.items():
   print(k, v)
# 7、get
print(d.get('kkkk'))

# 需要掌握的操作
dic = d.copy()
print(dic)
d.update({'k5': 5555, 'k4': 2441})
print(d)
res = d.pop('k4')
print(res)
print(d)
res = d.setdefault("k1", 6666666666)
print(d)
print(res)
5.4 总结
存多个值、无序、可变
d = {'k1': [], 'k2': []}
print(id(d['k1']))
print(id(d['k2']))
d = {}.fromkeys(['k1', 'k2'], [])
print(id(d['k1']))
print(id(d['k2']))
nums = [11, 22, 33, 44, 55, 66, 77, 88, 99, 1111]
for num in nums:
    if num > 66:
        d['k1'].append(num)
    else:
        d['k2'].append(num)
print(d)

s = 'hello alex hello alex say sb sb'
words = s.split()
d = {}
for word in words:
    if word not in d:
        d[word] = 1
    else:
        d[word] += 1
print(d)

六、集合类型

6.1 用途
去重(鸡肋)、关系运算(并集交集差集)
6.2 定义
在{}内用多个逗号分开放多个不可变类型
# 特点:
# 元素不可变、元素无序,元素唯一
s = {111, 333, 'sss', (11, 34, 'ff')}
print(s, type(s))
# 自己写代码去重(集合set去重鸡肋)
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'},
]
res = []
for item in l:
    # print(item)
    if item not in res:
        res.append(item)
print(res)
6.3 优先掌握的操作:
s = {111,222,333,'aaa','bbb'}
# 1、长度len
print(len(s))
# 2、成员运算in和not in
print(222 in s)
# 3、|并集
pythons = {'alex', 'egon', 'yuanhao', 'wupeiqi', 'gangdan', 'biubiu'}
linuxs = {'wupeiqi', 'oldboy', 'gangdan'}
print(linuxs | pythons)
# 4、&交集
print(linuxs & pythons)
# 5、-差集
print(pythons - linuxs)
# 6、^对称差集
print(pythons ^ linuxs)
# 7、==
s1 = {1, 2, 3}
s2 = {3, 2, 1}
print(s1 == s2)
# 8、父集:>,>= ; 子集:<,<=
s1 = {1, 2, 3, 4, 5}
print(s1 > s2)
print(s2 < s1)
# 存多个值、无序、可变
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值