String Joining from Iterable containing Strings and ( NoneType / Undefined )
You can use filter(bool, your_list)
or filter(None, your_list)
to remove anything that evaluates to False when converted to a bool, such as False, None, 0, [], (), {}, '', maybe others.
You can use locals().get('mightnotexist')
or globals().get('mightnotexist')
, depending on whether the variable is expected to be local or global, to reference a variable that might not exist. These will return None if the variable doesn't exist.
Your code might become:
items = ('productX',
'deployment-package',
'1.2.3.4',
locals().get('idontexist'),
globals().get('alsonotexist'),
None,
None,
'')
'-'.join(filter(bool, items))
If you want to keep the number of items constant (for instance because you want to output to a spreadsheet where the list is a row and each item represents a column), use:
your_list = ['key', 'type', 'frequency', 'context_A', None, 'context_C']
'\t'.join(str(item) for item in your_list)
BTW this is also the way to go if any of the items you want to join are integers.
You can use a comprehension to populate your iterable with a conditional checking that values have a truthy value.
your_list = [
'productX',
'deployment-package',
'1.2.3.4',
None,
None,
None,
]
'-'.join(item for item in your_list if item)