Python 3.9是现代程序语言Python的最新版本,它为开发者提供了很多有用和新的特性。本文将介绍Python 3.9的一些重要特性和使用技巧。
Python3.9的嵌套字典合并方便了程序开发人员。假如有两个字典,你可以使用运算符"|"对它们进行合并。
dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} new_dict = dict1 | dict2 print(new_dict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Python3.9的字符串方法提供了更多选择,例如:removesuffix()和removeprefix()方法可用于删除字符串的开头或结尾的某些字符。
str1 = "Hello Python" new_str = str1.removesuffix("on") print(new_str) # "Hello Pyth" new_str = str1.removeprefix("He") print(new_str) # "llo Python"
还有一些小变化:int()函数现在支持二进制数前缀"0b",小数点(.)后可以使用下划线(_)作为分隔符。
print(int("0b11110", 2)) # 30 print(1_000_000.0) # 1000000.0
Flat is better than nested, Python 3.9提供了新的结构体——denumerate提供了更直观的嵌套解决方案。
from collections import namedtuple Student = namedtuple('Student', ['name', 'age']) s1 = Student('Tom', 25) s2 = Student('John', 22) Cohort = namedtuple('Cohort', ['name', 'students']) cohort1 = Cohort('Class1', [s1, s2]) for i, cohort in enumerate([cohort1]): for j, student in denumerate(cohort.students): print(i, j, student.name)
Python3.9的改进使开发人员编写代码更方便和易读。
上一篇 html文字放在图片右边代码
下一篇 python3。8编程