简体   繁体   English

在Python中使用Bash $ {var:-default}等价物?

[英]Bash ${var:-default} equivalent in Python?

What's the simplest way to perform default variable substitution? 执行默认变量替换的最简单方法是什么?

x = None
... (some process which may set x)
if x is None: use_x = "default"
else:         use_x = x

Is there any way of writing this in one line? 有没有办法在一行中写这个?

You can use a conditional expression : 您可以使用条件表达式

use_x = "default" if x is None else x

You could use a dict defaulting to x if the key did not exist to resemble the bash syntax but the conditional would be the idiomatic way: 你可以使用dict默认为x如果键不存在以类似于bash语法但条件将是惯用的方式:

use_x = {None: "default"}.get(x, x)

You can use 您可以使用

x = x or "default"

in Python. 在Python中。 This is not exactly the same, since it depends on Python definition of truth values , which differs from Bash's distinction of set and unset values. 这不完全相同,因为它依赖于Python对真值的定义,这与Bash对set和unset值的区别不同。 But it's a close approximation and the idiomatic Python way of solving the same general problem of testing for unset values. 但这是一个近似的近似和惯用的 Python方法,解决了测试未设置值的相同的一般问题。

If you are specifically interested in only substituting None values, then this code will yield the wrong result, and Padraic's solution is more appropriate. 如果您对仅替换None特别感兴趣,那么此代码将产生错误的结果,而Padraic的解决方案更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM