[Tutor] neat join

Kent Johnson kent37 at tds.net
Mon Oct 24 11:55:21 CEST 2005


Vincent Gulinao wrote:
> is there any simple syntax for joining strings such that if any (or all) 
> of the params is white space or None, it won't be included in the 
> resulting string?
> 
> e.g. str1, str2, str3 = "foo", "bar", None, if delimiter is " " would 
> result to "foo bar"; str1, str2 = None, None would result to None.

If all your values are in a list, use a list comprehension to strip out the empty ones and join() to make a string:

 >>> def joinNoWs(lst):
 ...   lst = [s for s in lst if s and s.strip() ]
 ...   if lst:
 ...     return ' '.join(lst)
 ...   return None
 ...
 >>> joinNoWs( [ "foo", "bar", None ] )
'foo bar'
 >>> joinNoWs( [ None, None ] )

If it's OK to return an empty string instead of None when all the inputs are empty, you can do this in one line:

 >>> def joinNoWs(lst):
 ...   return ' '.join( [s for s in lst if s and s.strip()] )
 ...
 >>> joinNoWs( [ None, None ] )
''
 >>> joinNoWs( [ "foo", "bar", None ] )
'foo bar'

Kent

-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list