48

Python3.8 新特性:赋值表达式

 4 years ago
source link: https://www.tuicool.com/articles/BJRFrmQ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

赋值表达式

赋值表达式的语法是:“ name := expression ”,这个曾经引起很大争议特性,最终还是加入到了Python3.8。不过它也仅仅只是一个锦上添花的特性,可以通过一个例子了解它的使用场景。

>>> import re

>>> data = "hello123world"
>>> match = re.search("(\d+)", data)  # 3
>>> if match:                         # 4
...     num = match.group(1)
... else:
...     num = None
>>> num
'123'

上面是一个用正则表达式提取字符串中数字部分的操作,在Python3.8中,可以将第3、4行代码合并成一行代码,给变量赋值的同时,它还是一个表达式。相比之前的版本,代码少了一行。

>>> if match:=re.search("(\d+)", data):
...     num = match.group(1)
... else:
...     num = None
...
>>> num
'123'

这样看起来代码确实精简了一点点,但是,这样的特性对开发者来说,只能说是一个不痛不痒的功能,至少对我来是这样。

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

vQremuy.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK