The inverse of .join

Neil Cerutti neilc at norwich.edu
Fri Jun 18 08:54:23 EDT 2010


On 2010-06-18, Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:
> On Thu, 17 Jun 2010 20:03:42 +0000, Neil Cerutti wrote:
>> I'm currently using the following without problems, while
>> reading a data file. One of the fields is a comma separated
>> list, and may be empty.
>> 
>>   f = rec['codes']
>>   if f == "":
>>     f = []
>>   else:
>>     f = f.split(",")
>> 
>> I just wondered if something smoother was available.
>
> Seems pretty smooth to me. What's wrong with it? I assume
> you've put it into a function for ease of use and reduction of
> code duplication.

The part that's wrong with it, and it's probably my fault, is
that I can never think of it. I had to go dig it out of my code
to remember what the special case was.

> You could also use the ternary operator, in which case it's a
> mere two- liner and short enough to inline wherever you need
> it:
>
> f = rec['codes']
> f = f.split(",") if f else []

That's pretty cool.

Thanks to everybody for their thoughts.

-- 
Neil Cerutti



More information about the Python-list mailing list