“海象操作员”分配的多个条件

Sha*_*ney 2 python python-3.8 python-assignment-expression

我想知道是否可以使用“海象运算符”根据某些条件以及现有条件来分配值。例如,post_url如果该字符串包含某个子字符串,则将该字符串分配给:

if post_url := data.get("Post url") and ("youtube" in data.get("Post url")):
    # Do something with post_url
else:
    # Do something else
Run Code Online (Sandbox Code Playgroud)

然而,这只是post_url由于操作的评估而分配布尔值and

jon*_*rpe 9

您可以使用括号按照您想要的方式对其进行分组,您甚至不需要重复data.get

if (post_url := data.get("Post url")) and "youtube" in post_url:
    # Do something with post_url
else:
    # Do something else
Run Code Online (Sandbox Code Playgroud)

这将为任一方式分配一个值post_url,以便您可以访问或不包含在块中的NoneURL 。"youtube"else