Re: using split for a string : error

Discussion in 'Python' started by Tobias M., Jan 24, 2013.

  1. Tobias M.

    Tobias M. Guest

    Hi,

    do a "print sp" after the split and you might see that the strings don't
    look as you expected. There might be leading or trailing whitespaces in
    the splitted strings and in sp[10] there probably is a line break "\n"
    at the end.
    To remove those unwanted characters you could use the strip() function.

    So your code could be:

    if sp[9].strip() == sp[10].strip():
    print "Same class"
    else:
    print "Different class"

    At least this works for me when I tried it...

    Am 24.01.2013 11:37, schrieb inshu chauhan:
    > Here I have a code which basically reads a csv file, tries to compare
    > the last 2 items in each line of the file.
    >
    > f = open(r"Z:\modules\Feature_Vectors_300_Pclass.arff")
    > for l in f:
    > sp = l.split(",")
    > if len(sp) != 11:
    > print >> of, l,
    >
    > else:
    > #print sp[9], sp[10]
    > if sp[9] == sp[10]:
    > print " Same class"
    > else :
    > print "Different class"
    >
    > f.close()
    >
    > 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 ?
    >
    >
    Tobias M., 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:
    451
  2. Carlos Ribeiro
    Replies:
    11
    Views:
    685
    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:
    202
    Florian Gross
    Dec 28, 2004
  4. Sam Kong
    Replies:
    5
    Views:
    227
    Rick DeNatale
    Aug 12, 2006
  5. Stanley Xu
    Replies:
    2
    Views:
    583
    Stanley Xu
    Mar 23, 2011
Loading...

Share This Page