I am basically looking for the Python equivalent to this VB/VBA string operation:
FullName开发者_如何学JAVA = LastName & ", " + FirstName
In VB/VBA +
and &
are both concatenation operators, but they differ in how they handle a Null value:
"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.
Is there a one-line idiomatic way to do this in 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.The following line can be used to concatenate more not-None elements:
FullName = ', '.join(filter(None, (LastName, FirstName)))
FullName = LastName + (", " + FirstName if FirstName else "")
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
精彩评论