Re: using split for a string : error

Discussion in 'Python' started by Chris Angelico, Jan 24, 2013.

  1. On Thu, Jan 24, 2013 at 9:37 PM, inshu chauhan <> wrote:
    > For me I think the programme is logically correct, but its giving me results
    > which are strange.
    > It is Printing " Different Class" even when sp[9] is equal to sp[10] and
    > "Same class" when sp[9] is not equal to sp[10]. and sp[9] and sp[10] are
    > simple integers like 3, 3, 4 ,4.
    >
    > I have a little understanding why the programme is behaving like this ?


    Without your data file I can't advise, but here's a couple of things
    to try. I see you've tried displaying the values:

    #print sp[9], sp[10]

    Try this version:

    print repr(sp[9]), repr(sp[10])

    That'll make it obvious if, for instance, there are leading/trailing spaces.

    The other thing you may want to consider, if the values are supposed
    to be integers, is to convert them to Python integers before
    comparing. Currently, you're working with strings. Replace this:

    if sp[9] == sp[10]:

    with this:

    if int(sp[9]) == int(sp[10]):

    That will consider "1" and "1 " to be the same, since they'll both be
    parsed as the integer 1. Alternatively, consider what Tobias said and
    explicitly strip spaces. Either way, displaying repr() of the strings
    (or printing the whole of sp, as Tobias suggests) will show you what's
    needed.

    ChrisA
     
    Chris Angelico, Jan 24, 2013
    #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. Replies:
    2
    Views:
    470
  2. Carlos Ribeiro
    Replies:
    11
    Views:
    702
    Alex Martelli
    Sep 17, 2004
  3. trans.  (T. Onoma)

    split on '' (and another for split -1)

    trans. (T. Onoma), Dec 27, 2004, in forum: Ruby
    Replies:
    10
    Views:
    218
    Florian Gross
    Dec 28, 2004
  4. Sam Kong
    Replies:
    5
    Views:
    246
    Rick DeNatale
    Aug 12, 2006
  5. Stanley Xu
    Replies:
    2
    Views:
    618
    Stanley Xu
    Mar 23, 2011
Loading...

Share This Page