Python 使用可选分隔符连接字符串和无/字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3752240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Join string and None/string using optional delimiter
提问by mwolfe02
I am basically looking for the Python equivalent to this VB/VBA string operation:
我基本上是在寻找与此 VB/VBA 字符串操作等效的 Python:
FullName = LastName & ", " + FirstName
In VB/VBA +and &are both concatenation operators, but they differ in how they handle a Null value:
在 VB/VBA 中+和&都是连接运算符,但它们处理 Null 值的方式不同:
"Some string" + Null ==> Null
"Some string" & Null ==> "Some string"
This hidden feature allows for the first line of code I wrote to include a comma and space between the required LastName and the optional FirstName values. If FirstName is Null (Null is the VB/VBA equiv of Python's None), FullName will be set to LastName with no trailing comma.
此隐藏功能允许我编写的第一行代码在必需的姓氏和可选的名字值之间包含逗号和空格。如果 FirstName 为 Null(Null 是 Python 的 None 的 VB/VBA 等效项),FullName 将设置为 LastName,不带尾随逗号。
Is there a one-line idiomatic way to do this in Python?
在 Python 中是否有一种单行惯用的方法来做到这一点?
Technical Note:
gnibbler's and eumiro's answers are not strictly the equivalent of VB/VBA's +and &. Using their approaches, if FirstName is an empty string ("") rather than None, there will be no trailing comma. In almost all cases this would be preferable to VB/VBA's result which would be to add the trailing comma with a blank FirstName.
技术说明:
gnibbler 和 eumiro 的答案并不严格等同于 VB/VBA+和&. 使用他们的方法,如果 FirstName 是空字符串 ("") 而不是 None,则不会有尾随逗号。在几乎所有情况下,这都优于 VB/VBA 的结果,即添加带有空白名字的尾随逗号。
采纳答案by John La Rooy
FullName = LastName + (", " + FirstName if FirstName else "")
回答by eumiro
The following line can be used to concatenate more not-None elements:
以下行可用于连接更多的 not-None 元素:
FullName = ', '.join(filter(None, (LastName, FirstName)))
回答by SilentGhost
Simple ternary operator would do:
简单的三元运算符可以:
>>> s1, s
('abc', None)
>>> print(s if s is None else s1 + s)
None
>>> print(s1 if s is None else s1 + s)
abc

