Python 2.7终结于7个月后,这是你需要了解的3.X炫酷新特性
作者:CQITer小编 时间:2019-05-20 21:22
许多人在了解到 Python 2.7 即将停止维护后,都开始将他们的 Python 版本从 2 切换到 3。截止到 5 月 19 号上午 10 点,Python 2.7 将终结于...

在这一段时间中,很多优秀开源项目与库已经停止了对 2.7 的支持。例如到今年 1 月份,NumPy 将停止支持 Python 2;到今年年末,Ipython、Cython 和 Pandas 等等都将陆续停止支持 Python 2。
虽然我们都往 3.X 迁移,但许多人编写的 Python 3 代码仍然看起来像 Python 2 一样,只不过加入了一些括号或改了些 API。在本文中,作者将展示一些令人激动的 Python 3.X 新特性。这些特性或方法都是 Python 3 各个版本中新加的,它们相比传统的 Python 方法,更容易解决实践中的一些问题。
所有的示例都是在 Python 3.7 的环境下编写的,每个特性示例都给出了其正常工作所需的最低的 Python 版本。
格式化字符串 f-string(最低 Python 版本为 3.6)
在任何的编程语言中,不使用字符串都是寸步难行的。而为了保持思路清晰,你会希望有一种结构化的方法来处理字符串。大多数使用 Python 的人会偏向于使用「format」方法。
user = "Jane Doe"
action = "buy"
log_message = 'User {} has logged in and did an action {}.'.format(
user,
action
)
print(log_message)
# User Jane Doe has logged in and did an action buy.
除了「format」,Python 3 还提供了一种通过「f-string」进行字符串插入的灵活方法。使用「f-string」编写的与上面功能相同的代码是这样的:
user = "Jane Doe"
action = "buy"
log_message = f'User {user} has logged in and did an action {action}.'
print(log_message)
# User Jane Doe has logged in and did
相比于常见的字符串格式符 %s 或 format 方法,f-strings 直接在占位符中插入变量显得更加方便,也更好理解。
路径管理库 Pathlib(最低 Python 版本为 3.4)
f-string 非常强大,但是有些像文件路径这样的字符串有他们自己的库,这些库使得对它们的操作更加容易。Python 3 提供了一种处理文件路径的抽象库「pathlib」。如果你不知道为什么应该使用 pathlib,请参阅下面这篇 Trey Hunner 编写的炒鸡棒的博文:
「https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/」
from pathlib import Path
root = Path('post_sub_folder')
print(root)
# post_sub_folder
path = root / 'happy_user'
# Make the path absolute
print(path.resolve())
# /home/weenkus/Workspace/Projects/DataWhatNow-Codes/how_your_python3_should_look_like/post_sub_folder/happy_user
如上所示,我们可以直接对路径的字符串进行「/」操作,并在绝对与相对地址间做转换。
类型提示 Type hinting(最低 Python 版本为 3.5)
静态和动态类型是软件工程中一个热门的话题,几乎每个人 对此有自己的看法。读者应该自己决定何时应该编写何种类型,因此你至少需要知道 Python 3 是支持类型提示的。
def sentence_has_animal(sentence: str) -> bool:
return "animal" in sentence
sentence_has_animal("Donald had a farm without animals")
# True
枚举(最低 Python 版本为 3.4)



