Checking if elements are empty

Steve Holden steve at holdenweb.com
Tue Sep 11 08:46:18 EDT 2007


Hamilton, William wrote:
>> From: Steve Holden
>> Neil Cerutti wrote:
>>> On 2007-09-10, Chris Mellon <arkanes at gmail.com> wrote:
>>>> On 9/10/07, Neil Cerutti <horpner at yahoo.com> wrote:
>>>>> Agreed; but I prefer 'if y[0] == ""', absent more context and
>>>>> better names.
>>>> Probably should use u"" if you're going to take that route, as
>>>> this will fail spuriously if y[0] contains a unicode string
>>>> that can't be implicitly converted to ascii. Personally, I
>>>> prefer the boolean check and I'll let operations fail elsewhere
>>>> if there's a type mismatch.
>>> I have a quibble not with the functionality of the boolean check,
>>> but with its expressiveness. if y[0] == "" expresses more, i.e.,
>>> that I expect y[0] to contain a Python byte string.
>>>
>> I have a quibble with a test that will raise an exception when the
>> anticipated condition is true. Your test is patently absurd, as you
>> would have discovered had you bothered to try it:
>>
>>  >>> y = ""
>>  >>> if y[0] == "":
>> ...   print "True"
>> ... else:
>> ...   print "False"
>> ...
>> Traceback (most recent call last):
>>    File "<stdin>", line 1, in <module>
>> IndexError: string index out of range
>>  >>>
>>
>> Further, when the string is *not* the null string the test will always
>> return False, as you will be comparing two strings of unequal length.
>>
>> So, absent a solution that works, len(y) == 0 looks pretty good.
> 
> 
> Going back to the OP, the problem is taking a string such as
>>>> x = '  \t"ff'
> then splitting that string like this
>>>> y = x.split('\t')
> 
> The question is, does the first element of the list y contain an empty
> string or not?  In this case, the logic in the following conditional is
> perfectly valid.
>>>> if y[0] == "":
> ...    print "True"
> ... else
> ...    print "False"
> 
> (len(y[0]) == 0) would also work, and is the solution you originally
> gave the OP.  
> 
Aah, list of strings, right. Thanks.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list