Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 months ago.
The community reviewed whether to reopen this question 10 months ago and left it closed:
Original close reason(s) were not resolved
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(17)
可能最短的是
str(s or '')
因为 None 为 False,如果 x 为 false,则“x or y”返回 y。 有关详细说明,请参阅布尔运算符。 它很短,但不是很明确。
Probably the shortest would be
str(s or '')
Because None is False, and "x or y" returns y if x is false. See Boolean Operators for a detailed explanation. It's short, but not very explicit.
如果您确实希望函数的行为类似于
str()
内置函数,但在参数为 None 时返回空字符串,请执行以下操作:If you actually want your function to behave like the
str()
built-in, but return an empty string when the argument is None, do this:如果您知道该值始终是字符串或 None:
If you know that the value will always either be a string or None:
return s 或 ''
可以很好地解决您所说的问题!return s or ''
will work just fine for your stated problem!更新:
我现在主要使用这个方法:
如果 some_string 不是
NoneType
,则or
会短路并返回它,否则返回空字符串。旧:
Max 函数在 python 2.x 中有效,但在 3.x 中无效:
UPDATE:
I mainly use this method now:
If some_string was not
NoneType
, theor
would short circuit there and return it, otherwise it returns the empty string.OLD:
Max function worked in python 2.x but not in 3.x:
功能方式(单行)
Functional way (one-liner)
在其他一些答案的基础上做这件事的简洁的一句台词:
或者甚至只是:
A neat one-liner to do this building on some of the other answers:
or even just:
如果您需要与 Python 2.4 兼容,请对上述内容进行变体
Variation on the above if you need to be compatible with Python 2.4
如果是关于格式化字符串,可以执行以下操作:
If it is about formatting strings, you can do the following:
在下面解释的场景中,我们总是可以避免类型转换。
在上面的示例中,如果变量 customer 的值为 None,则在分配给“name”时会进一步进行转换。 'if' 子句中的比较总是会失败。
上面的例子将正常工作。 当从 URL、JSON 或 XML 获取值,甚至值需要进一步类型转换以进行任何操作时,这种情况非常常见。
We can always avoid type casting in scenarios explained below.
In the example above in case variable customer's value is None the it further gets casting while getting assigned to 'name'. The comparison in 'if' clause will always fail.
Above example will work properly. Such scenarios are very common when values are being fetched from URL, JSON or XML or even values need further type casting for any manipulation.
使用短路评估:
由于 + 对字符串不是一个很好的操作,所以最好使用格式字符串:
Use short circuit evaluation:
Since + is not a very good operation on strings, better use format strings:
与 Vinay Sajip 的答案相同,带有类型注释,这消除了对
str()
结果的需要。Same as Vinay Sajip's answer with type annotations, which precludes the needs to
str()
the result.如果您使用的是 python v3.7,请使用 F 字符串
Use F string if you are using python v3.7