What better way to concatenate string in python? What better way to concatenate string in python? python python

What better way to concatenate string in python?


# Concatenates a and b with ' - ' or Coalesces them if one is None'-'.join([x for x in (a,b) if x])

Edit
Here are the results of this algorithm (Note that None will work the same as ''):

>>> '-'.join([x for x in ('foo','bar') if x])'foo-bar'>>> '-'.join([x for x in ('foo','') if x])'foo'>>> '-'.join([x for x in ('','bar') if x])'bar'>>> '-'.join([x for x in ('','') if x])''

*Also note that Rafael's assessment, in his post below, only showed a difference of .0002 secs over a 1000 iterations of the filter method, it can be reasoned that such a small difference can be due to inconsistencies in available system resources at the time of running the script. I ran his timeit implementation over several iteration and found that either algorithm will be faster about 50% of the time, neither by a wide margin. Thus showing they are basically equivalent.


How about something simple like:

# if I always need a string even when `a` and `b` are both null,# I would set `output` to a default beforehand.# Or actually, as Supr points out, simply do `a or b or 'default'`if a and b:    output = '%s - %s' % (a, b)else:    output = a or b

Edit: Lots of interesting solutions in this thread. I chose this solution because I was emphasizing readability and quickness, at least in terms of implementation. It's not the most scalable or interesting solution, but for this scope it works, and lets me move on to the next problem very quickly.


Wow, seems like a hot question :p My proposal:

' - '.join(filter(bool, (a, b)))

Which gives:

>>> ' - '.join(filter(bool, ('', '')))''>>> ' - '.join(filter(bool, ('1', '')))'1'>>> ' - '.join(filter(bool, ('1', '2')))'1 - 2'>>> ' - '.join(filter(bool, ('', '2')))'2'

Obviously, None behaves like '' with this code.