-5

I am writing an application on PyCharm in Python 2.6.6 and not getting the output I expect:

if VAR1 != row2:
    print "Status 1: %s" %VAR1
    print "Status 2: %s" %row2
    print "%s != %s" % (VAR1, row2)

Output:

Status 1: 3
Status 2: 3
3 != (3L,)

Does somebody know what's happening here?

Foon
  • 5,830
  • 11
  • 38
  • 41
  • what are VAR1 and row2? – Ezer K Dec 31 '15 at 13:52
  • 3
    What's strange about it? – Iron Fist Dec 31 '15 at 13:53
  • @EzerK they are two different variable witch i catch from select command. – user5734100 Dec 31 '15 at 13:57
  • @IronFist in Status 2 row2 is 3 and the last line row2 is (3L,). – user5734100 Dec 31 '15 at 13:59
  • try to be more specific, that is the source of your strange output, check for yourself with other random vars – Ezer K Dec 31 '15 at 14:01
  • @user5734100 `VAR1` is an `INTEGER` and `row2` is a SQL list (returned as a Python tuple) that was returned from a query which has only one element. – erip Dec 31 '15 at 14:02
  • @PM2Ring It's a python tuple, but a SQL list. Edited my comment. – erip Dec 31 '15 at 14:05
  • 1
    @erip: Ah, rightio. I didn't see any mention of SQL by the OP, but I guess "select command" is a clue. :) – PM 2Ring Dec 31 '15 at 14:06
  • I think this has the guts of a good question, but it's not being asked the right way. – erip Dec 31 '15 at 14:11
  • FWIW, this potentially confusing behaviour is one of the reasons that `%`-style formatting is now discouraged and modern Python practice favours the use of `.format`, as mentioned in http://stackoverflow.com/questions/1455602/printing-tuple-with-string-formatting-in-python (but I still like the old style :) ). – PM 2Ring Dec 31 '15 at 14:18

1 Answers1

3

row2 is a tuple with 1 element. the % formatting of a string can be used with a single value or a tuple of one or more values.

In print "Status 2: %s" %row2 the tuple is unpacked and the sole element is used. In print "%s != %s" % (VAR1, row2) you have packed the tuple row2 in another tuple, so the second %s displays the representation of this tuple, e.g. (3,).

Daniel
  • 40,885
  • 4
  • 53
  • 79