Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What better way to concatenate string in python?

Understand "better" as a quicker, elegant and readable.

I have two strings (a and b) that could be null or not. And I want concatenate them separated by a hyphen only if both are not null:

a - b

a (if b is null)

b (where a is null)

like image 871
Shankar Cabus Avatar asked Mar 12 '13 12:03

Shankar Cabus


3 Answers

# 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.

like image 133
Hoopdady Avatar answered Sep 23 '22 23:09

Hoopdady


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.

like image 29
toxotes Avatar answered Sep 23 '22 23:09

toxotes


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.

like image 43
icecrime Avatar answered Sep 25 '22 23:09

icecrime