Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join string and None/string using optional delimiter

Tags:

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.

like image 275
mwolfe02 Avatar asked Sep 20 '10 14:09

mwolfe02


People also ask

How do you join none in Python?

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.

Can you concatenate a string with null?

To concatenate null to a string, use the + operator.

How do I append a null to a string?

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.


2 Answers

The following line can be used to concatenate more not-None elements:

FullName = ', '.join(filter(None, (LastName, FirstName))) 
like image 52
eumiro Avatar answered Sep 17 '22 20:09

eumiro


FullName = LastName + (", " + FirstName if FirstName else "") 
like image 40
John La Rooy Avatar answered Sep 20 '22 20:09

John La Rooy