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)
Understand "better" as a quicker, elegant and readable. I have two strings (
|
|||||||||||||||||||||
|
Edit
*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 serveral 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:
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:
Which gives:
Obviously, |
|||||||||||||
|
Here is one option:
EDIT: As pointed by mgilson, this code would fail on with
|
|||||||||
|
I just wanted to offer toxotes' solution rewritten as a one liner using
|
|||
|
There's a lot of answers here :) The two best answers (performance and clean code in one line) are the answers of @icecrime and @Hoopdady Both asnwers results equally, the only difference is performance.
So let's do a benchmark :)
But, as @mgilson said, using
So, the best result is the answer gave by @icecrime with the suggestion from @mgilson:
The performance difference is in milliseconds per 1000 iterations (microseconds per iteration). So these two methods have a quite equals performance, and, for almost any project you could choose any one; In case your project must have a better performance, considering microseconds, you could follow this benchmark :) |
|||||||||||||||||
|
Try this:
Or
|
|||||||||||||||||
|
Something pythonian, readable and elegant:
And fast too ;) |
|||
|
I would do it like this:
|
|||
|