RE: How to check if a string is empty in python?

Discussion in 'Python' started by Hamilton, William, May 4, 2007.

  1. > -----Original Message-----
    > From:
    >
    > On May 4, 5:02 am, Jaswant <> wrote:
    > > This is a simple way to do it i think
    > >
    > > s=hello
    > >
    > > >>> if(len(s)==0):

    > >
    > > ... print "Empty"
    > > ... else:
    > > ... print s
    > > ...
    > > hello

    >
    > But you are still making the assumption that s is a string.
    > (BTW, you need quotes around your example.)
    >
    > For example:
    >
    > >>> print a,b

    > 11 11
    >
    > Can you tell which one is the string? I.e., which one had quotes
    > around it?
    >
    > If you correctly assume that it was b, then yes, your example works.
    >
    > >>> print len(b)

    > 2
    >
    > If you incorrectly assume it was a, then the example doesn't work.
    >
    > >>> print len(a)

    > Traceback (most recent call last):
    > File "<pyshell#8>", line 1, in <module>
    > print len(a)
    > TypeError: object of type 'int' has no len()
    >
    > You have to know that a variable is a string before you try to do a
    > len().
    >
    > Dynamic typing is a feature, but that doesn't relieve you of the
    > necessary tests.


    Your point would be important if the question were "How can I tell if x
    is an empty string?" On the other hand, "How to check if a string is
    empty?" implies that the OP already knows it is a string. Maybe he's
    been using string methods on it, maybe he got it from a function that he
    knows provides a string. Maybe he's checked its type. It doesn't really
    matter, if he's aware it is a string he doesn't have to test it for
    stringness.


    ---
    -Bill Hamilton
    Hamilton, William, May 4, 2007
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Marcia Hon

    Check if a directory is empty and empty it

    Marcia Hon, Feb 8, 2004, in forum: C Programming
    Replies:
    8
    Views:
    572
    Dave Thompson
    Feb 14, 2004
  2. Replies:
    5
    Views:
    929
    X-Centric
    Jun 30, 2005
  3. Replies:
    31
    Views:
    37,020
    John Machin
    May 5, 2007
  4. Tzury Bar Yochay
    Replies:
    1
    Views:
    402
    Gabriel Genellina
    Mar 24, 2008
  5. Savvoulidis Iordanis

    Empty gridview cells and checking for empty string

    Savvoulidis Iordanis, Sep 5, 2008, in forum: ASP .Net
    Replies:
    1
    Views:
    518
    Savvoulidis Iordanis
    Sep 5, 2008
Loading...

Share This Page