Concatenate if string might be null?

I need to concatenate some strings, however one of the strings may be blank.

The function takes multiple address fields (Street Address, Unit/Suite Number, City, State) and concatenates them into a string to pass into an API call.

Since most addresses don’t have a unit/suite number (street_line_2), I need a way to allow this string to be blank, but still concatenate the rest of the strings.

address=doc.street_line_1 + " " + doc.street_line_2 + ", " + + ", " + doc.state

Hi @jeremy58, you might filter() the street lines for truthy values and then join() them like so:

# Concatenate the filtered street lines with a space separator
street_lines = ' '.join(filter(None, [doc.street_line_1, doc.street_line_2))
# Concatenate the result and the remaining parts with a comma separator
address = ', '.join([street_lines,, doc.state)
1 Like

Can also use list comprehension:

address = ' '.join(
    [v for v in [doc.street_line_1, doc.street_line_2] if v != None] + [, doc.state])