Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Joining from Iterable containing Strings and ( NoneType / Undefined )

Tags:

python

I am looking for a clean way to combine variables into a single string with a predefined separator. The problem is that sometimes some of these variables wont always exist or can be set to None. I cant have the separator string duplicate either. Example of problem:

# This works because I have all strings
str('-').join(('productX', 'deployment-package', '1.2.3.4'))
# 'productX-deployment-package-1.2.3.4'

# But I have more args that might be None / or not exist like and that breaks
str('-').join(('productX', 'deployment-package', '1.2.3.4', idontexist, alsonotexist))
str('-').join(('productX', 'deployment-package', '1.2.3.4', None, None, None))

# If I set the other missing variables to empty strings, I get duplicated joiners
str('-').join(('productX', 'deployment-package', '1.2.3.4', '', '', ''))
# 'productX-deployment-package-1.2.3.4---'

Is there a nice clean way to do this?

like image 615
unixunion Avatar asked Jun 20 '12 12:06

unixunion


2 Answers

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)
like image 57
dm03514 Avatar answered Nov 15 '22 23:11

dm03514


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.

like image 27
Tayo Avatar answered Nov 16 '22 01:11

Tayo