python3数据类型及操作
# Number(数字)
counter = 100 # 整型变量 miles = 1000.0 # 浮点型变量 num_complex = complex(1.5, 2.5) print(counter) # 100 print(miles) # 1000.0 print(num_complex) # (1.5+2.5j) # 数字类型转换 print(float(counter)) # 100.0 print(int(miles)) # 1000 print(complex(counter)) # (100+0j) print(complex(counter, miles)) # (100+1000j) print(5 + 4) # 加法 输出 9 print(4.3 - 2) # 减法 输出 2.3 print(3 * 7) # 乘法 输出 21 print(2 / 4) # 除法,得到一个浮点数 输出 0.5 print(2 // 4) # 除法,得到一个整数 输出 0 print(17 % 3) # 取余 输出 2 print(2**5) # 乘方 输出 32
# String(字符串)
创建字符串可以使用单引号、双引号、三单引号和三双引号,其中三引号可以多行定义字符串
str = "Python学习" print(len(str)) # 8 # 切片 print( str[0], str[-1], str[3:], str[::-1], str[::-2] ) # 'P', '习', 'hon学习', '习学nohtyP', '习nhy' # 替换,还可以使用正则表达式替换 print(str.replace("Python", "Java")) # 'Java学习' # 查找 print(str.count("P")) # 1 返回子串在str中出现的次数 print(str.find("P")) # 0, 返回第一次出现的子串的下标 print(str.rfind("P")) # 0, 返回最后一次出现的子串的下标 print(str.find("我")) # -1, 查找不到返回-1 print(str.find("h", 2)) # 3, 设定下标2开始查找 print(str.index("y")) # 1, 返回第一次出现的子串的下标 print(str.rindex("y")) # 1, 返回最后一次出现的子串的下标 try: print(str.index("我")) # 查找不到会抛出异常 except ValueError: print("'{}'字符串中没有'{}'".format(str, "我")) # 转大小写 print(str.upper()) # 'PYTHON学习' print(str.lower()) # 'python学习' print(str.swapcase()) # 'pYTHON学习', 大小写互换 print("good".capitalize()) # 'Good', 首字母大写,其它字母小写 print("a good day".title()) # 'A Good Day', 每个词(以空格分隔)的首字母大写 # 判断 print(str.istitle()) # True,如果所有的词的首字母都是大写返回True print(str.isupper()) # False,如果所有的字符都是大写字母返回True print(str.islower()) # False,如果所有的字符都是小写字母返回True print("abc123".isalnum()) # True, 如果所有的字符都是字母或数字返回True print("and".isalpha()) # True,如果所有的字符都是字母返回True print("123".isdigit()) # True,如果所有的字符都是数字返回True print(" ".isspace()) # True,如果所有的字符都是空格返回True str1 = " Python 学习 " # 去空格与补齐 print("'{}'".format(str1.strip())) # 'Python 学习' 去除字符串两边的空格 print("'{}'".format(str1.lstrip())) # 'Python 学习 ' 去除字符串左边的空格 print("'{}'".format(str1.rstrip())) # ' Python 学习' 去除字符串右边的空格 print("'{}'".format(str.center(10))) # ' Python学习 ' 返回长度为width的字符串,在原字符串的两边补空格 print("'{}'".format(str.ljust(10))) # 'Python学习 ' 返回长度为width的字符串,在原字符串的右边补空格 print("'{}'".format(str.rjust(10))) # ' Python学习' 返回长度为width的字符串,在原字符串的左边补空格 # 格式化 print("'%s, %s'" % ("lily", 3)) # 'lily, 3' print("'{}, {}'".format("lily", 3)) # 'lily, 3' print("'{0}, {1}, {0}'".format("lily", 3)) # 'lily, 3, lily' print("'{name}: {age}'".format(age=3, name="lily")) # 'lily: 3' print("PI: {0:.3f}".format(math.pi)) # PI: 3.142 print("'{0:10} ==> {1:10d}'".format("lily", 123)) #'lily ==> 123' print("name: {0[name]:s}".format({"name": "lily"})) # name: lily # 连接与分割 print("hello" + " world") # hello world list = ["2023", "09", "09", "22:00"] str = "-".join(list) print(str) # '2023-09-09-22:00' print(str.split("-")) # ['2023', '09', '09', '22:00'] print(str.rsplit("-", 1)) # ['2023-09-09', '22:00'] # encode 将字符转换为字节 str = "学习Python" print(str.encode()) # 默认编码是 UTF-8 输出:b'\xe5\xad\xa6\xe4\xb9\xa0Python' print(str.encode("gbk")) # 输出 b'\xd1\xa7\xcf\xb0Python' # decode 将字节转换为字符 print(str.encode().decode("utf8")) # 输出 '学习Python' print(str.encode("gbk").decode("gbk")) # 输出 '学习Python' # json 格式数据 # json.dumps(obj) 序列化,obj 转换为 json 格式的字符串; str = json.dumps({"name": "jane"}) print(str, type(str)) # 字符串{"name": "jane"} <class 'str'> # json.dump(obj, fp) 序列化,将 obj 转换为 json 格式的字符串,将字符串写入文件; with open("files/tmp.txt", "w") as fp: json.dump({"name": "jane"}, fp) print(fp.closed) # True # json.loads(str) 反序列化,将 json 格式的字符串反序列化为一个 Python 对象; obj = json.loads('{"name": "jane"}') print(obj, type(obj)) # {'name': 'jane'} <class 'dict'> # json.load(fp) 反序列化,从文件中读取含 json 格式的数据,将之反序列化为一个 Python 对象。 with open("files/tmp.txt", "r") as fp: print(json.load(fp)) # {'name': 'jane'} print(fp.closed) # True
字符串前缀
r 前缀代表原始字符串
原始字符串会禁用转义字符的处理,字符串中的反斜杠 \ 不会被解释为转义序列。
常用于处理包含反斜杠的文件路径或正则表达式等情况,以避免转义字符的干扰。
f 前缀代表格式化字符串。
格式化字符串允许在字符串中插入变量或表达式的值,使用大括号 {} 包裹变量或表达式。
常用于创建动态字符串,特别是需要插入变量或表达式的情况。
u 前缀代表 Unicode 字符串
在 Python 2.x 中,u 前缀用于表示 Unicode 字符串。
在 Python 3.x 中,所有字符串都默认是 Unicode 字符串,因此通常不再需要显式使用 u。
b 前缀代表 Bytes 类型字符串
在 python3 中 str 和 bytes 转化:str.encode('utf-8') bytes.decode('utf-8')
# List(列表)
nl = [1, 2, 0, 3, 5] # 取值 print(nl[2], nl[-2], nl[3:], nl[::-1]) # 0 3 [3, 5] [5, 3, 0, 2, 1] # 赋值 nl[0] = 1 # 序列中包含元素的个数 print(len(nl)) # 5 # 判断 print(all(nl)) # False 所有元素都为True的话返回True print(any(nl)) # True 任一元素为True的话返回True print(10 in nl) # False 判断元素是否在列表中 # 统计 print(sum(nl)) # 11 序列中所有元素的和 print(min(nl)) # 0 序列中最小的元素 print(max(nl)) # 5 序列中最大的元素 # 查找 print(nl.count(5)) # 1 计数,看总共有多少个5 print(nl.count(10)) # 0 计数,看总共有多少个10 print(nl.index(3)) # 3 查询 nl 的第一个3的下标 # print(nl.index(10)) # 查找一个不存在列表中的元素ValueError # 添加 nl.append(6) # 在 nl 的最后增添一个新元素6 nl.insert(0, 9) # 在下标为0的位置插入9 nl.extend([7, 8]) print(nl) # [9, 1, 2, 0, 3, 5, 6, 7, 8] # 排序 nl.sort() print(nl) # [0, 1, 2, 3, 5, 6, 7, 8, 9] nl.reverse() print(nl) # [9, 8, 7, 6, 5, 3, 2, 1, 0] # 删除 print(nl.pop()) # 0 从nl中去除最后一个元素,并将该元素返回 print(nl) # [9, 8, 7, 6, 5, 3, 2, 1] nl.remove(2) # 从nl中去除第一个2 print(nl) # [9, 8, 7, 6, 5, 3, 1] # nl.remove(10) # 删除一个不存在列表中的元素ValueError del nl[0] # 删除元素 print(nl) # [8, 7, 6, 5, 3, 1] # 遍历 for val in nl: print(val) # 复制列表 nl_new = nl.copy() print(nl) # [8, 7, 6, 5, 3, 1] # 序列相加 print(nl + nl_new) # [8, 7, 6, 5, 3, 1, 8, 7, 6, 5, 3, 1] print(nl * 2) # [8, 7, 6, 5, 3, 1, 8, 7, 6, 5, 3, 1] # 转换为列表 print(list("python")) # ['p', 'y', 't', 'h', 'o', 'n'] print(list(("a", "b", "c", "d"))) # ['a', 'b', 'c', 'd'] # 分片赋值 name = list("Pyther") name[4:] = "on" print(name) # ['P', 'y', 't', 'h', 'o', 'n'] name[1:] = list("erl") print(name) # ['P', 'e', 'r', 'l']
# Tuple(元组)
元组的元素不能修改
tl = ("a", "b", "c", "d") print(tl[0]) # a print(tl[0:3]) # ('a', 'b', 'c') print(tl[::2]) # ('a', 'c') print(tl[::-2]) # ('d', 'b') # 元组中包含元素的个数 print(len(tl)) # 4 # 判断 print(all(tl)) # True 所有元素都为True的话返回True print(any(tl)) # True 任一元素为True的话返回True print("e" in tl) # False 判断元素是否在元组中 # 查找 print(tl.count("b")) # 1 计数,看总共有多少个b print(tl.index("b")) # 1 查询 nl 的第一个b的下标 tl1 = (1, 2, 0, 3, 5) # 统计 print(sum(tl1)) # 11 元组中所有元素的和 print(min(tl1)) # 0 元组中最小的元素 print(max(tl1)) # 5 元组中最大的元素 # 遍历 for val in tl: print(val) # 序列相加 print(tl + tl1) # ('a', 'b', 'c', 'd', 1, 2, 0, 3, 5) print(tl * 2) # ('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd') # 转换为元组 print(tuple(nl)) # (8, 7, 6, 5, 3, 1) print(tuple("python")) # ('p', 'y', 't', 'h', 'o', 'n')
# Sets(集合)
无序不重复元素的序列,不能被切片也不能被索引
st = {1, 0, 3, 4} # 集合中包含元素的个数 print(len(st)) # 4 # 添加 st.add(2) print(st) # {0, 1, 2, 3, 4} # 删除 st.discard(5) print(st) # {0, 1, 2, 3, 4} st.discard(2) print(st) # {0, 1, 3, 4} print(st.pop()) # 0 print(st) # {1, 3, 4} st.remove(3) print(st) # {1, 4} # 统计 print(sum(st)) # 8 集合中所有元素的和 print(min(st)) # 0 集合中最小的元素 print(max(st)) # 4 集合中最大的元素 # 判断 print(all(st)) # False 所有元素都为True的话返回True print(any(st)) # True 任一元素为True的话返回True print(6 in st) # False 判断元素是否在集合中 # 遍历 for val in st: print(val) # 空集合 st = set() print(len(st)) # 0
# Dictionary(字典)
字典是一种映射类型-键值对,字典的键必须为不可变类型,且不能重复
dic = {} dic = {"tom": 11, "sam": 57, "lily": 100} # 查询词典中的元素总数 print(len(dic)) # 3 # 检查键是否存在 print("tom" in dic) # True # 取值 print(dic["tom"]) # 11 print(dic.get("tom")) # 11 print(dic.get("rose", 45)) # 45 print(dic.keys()) # dict_values([11, 57, 100]) 返回dic所有的键 print(dic.values()) # dict_values([11, 57, 100]) 返回dic所有的值 print( dic.items() ) # dict_items([('tom', 11), ('sam', 57), ('lily', 100)]) 返回dic所有的元素(键值对) # 赋值 dic["tom"] = 30 dic["lilei"] = 99 dic.setdefault("jane", 40) dic.update({"jack": 90}) print(dic) # {'tom': 30, 'sam': 57, 'lily': 100, 'lilei': 99, 'jane': 40, 'jack': 90} # 遍历 for key in dic: print(key, dic[key]) # 浅拷贝: 引用对象 赋值 dict2 = dic # 拷贝 dict3 = dic.copy() # 删除 print(dic.popitem()) # ('jack', 90) print(dic.pop("lilei")) # 99 del dic["tom"] # 删除 dic 的 tom 元素 print(dic) # {'sam': 57, 'lily': 100, 'jane': 40} dic.clear() # 清空dic,dict变为{} print(dic) # {} seq = ("name", "age", "class") dic = dict.fromkeys(seq) print(dic) # {'name': None, 'age': None, 'class': None} dic = dict.fromkeys(seq, 10) print(dic) # {'name': 10, 'age': 10, 'class': 10}
分类:
python3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix