I am basically looking for the Python equivalent to this VB/VBA string operation:
FullName = 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.
To join multiple strings with possibly None values: Use the join() method with an optional delimiter. Use the filter() function to filter out any None values. The join() method returns a string which is the concatenation of the strings in the iterable.
To concatenate null to a string, use the + operator.
Using the String.concat() method is a good choice when we want to concatenate String objects. The empty String returned by the getNonNullString() method gets concatenated to the result, thus ignoring the null objects.
The following line can be used to concatenate more not-None elements:
FullName = ', '.join(filter(None, (LastName, FirstName)))
FullName = LastName + (", " + FirstName if FirstName else "")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With