check to see if value can be an integer instead of string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • nephish@xit.net

    #1

    check to see if value can be an integer instead of string

    Hello there,
    i need a way to check to see if a certain value can be an integer. I
    have looked at is int(), but what is comming out is a string that may
    be an integer. i mean, it will be formatted as a string, but i need to
    know if it is possible to be expressed as an integer.

    like this

    var = some var passed to my script
    if var can be an integer :
    do this
    else:
    change it to an integer and do something else with it.

    whats the best way to do this ?

    thanks, shawn

  • Claudio Grondi

    #2
    Re: check to see if value can be an integer instead of string

    nephish@xit.net wrote:[color=blue]
    > Hello there,
    > i need a way to check to see if a certain value can be an integer. I
    > have looked at is int(), but what is comming out is a string that may
    > be an integer. i mean, it will be formatted as a string, but i need to
    > know if it is possible to be expressed as an integer.
    >
    > like this
    >
    > var = some var passed to my script
    > if var can be an integer :
    > do this
    > else:
    > change it to an integer and do something else with it.
    >
    > whats the best way to do this ?
    >
    > thanks, shawn
    >[/color]
    No idea whats the best way to do and what in detail you want to achieve,
    but before others reply here, you can maybe start with something like this:

    intTheInt = None

    def checkIfStringCa nBeAnInteger(st rWithInt):
    global intTheInt
    try:
    intTheInt = int(strWithInt)
    if(type(intTheI nt)==type(1)):
    return True
    except:
    return False
    #:def

    lstTestCases = [
    '123', '789' , 'no', '1is2'
    ]

    for strWithInt in lstTestCases:
    intTheInt = None
    if checkIfStringCa nBeAnInteger(st rWithInt):
    print '"'+strWithInt+ '"', ' is an integer', intTheInt
    else:
    print '"'+strWithInt+ '"', ' is NOT an integer'


    Claudio

    Comment

    • nephish@xit.net

      #3
      Re: check to see if value can be an integer instead of string

      thanks for the reply, but wont python fail out if you try to make an
      integer out of what cant be an integer?
      like this :

      var = int(abc)

      wont this crash ?

      Comment

      • gry@ll.mit.edu

        #4
        Re: check to see if value can be an integer instead of string

        nephish@xit.net wrote:[color=blue]
        > Hello there,
        > i need a way to check to see if a certain value can be an integer. I
        > have looked at is int(), but what is comming out is a string that may
        > be an integer. i mean, it will be formatted as a string, but i need to
        > know if it is possible to be expressed as an integer.[/color]
        The "int" builtin function never returns any value but an integer.
        [color=blue]
        > like this
        >
        > var = some var passed to my script
        > if var can be an integer :
        > do this
        > else:
        > change it to an integer and do something else with it.[/color]

        Be careful about thinking "change it to an integer" in python. That's
        not what happens.
        The "int" builtin function looks at it's argument and, if possible,
        creates a new integer object
        that it thinks was represented by the argument, and returns that
        integer object.
        [color=blue]
        > whats the best way to do this ?[/color]

        The "pythonic" way might be something like:

        var=somestring
        try:
        do_something(in t(var)) #just try to convert var to integer and
        proceed
        except ValueError:
        do_something_el se(var) # conversion failed; do something with the
        raw string value

        The "int" builtin function tries to make an integer based on whatever
        argument is supplied.
        If if can not make an integer from the argument, it raises a ValueError
        exception.
        Don't be afraid of using exceptions in this sort of situation. They
        are pretty fast, and
        ultimately clearer than a lot of extra "if" tests.

        But do please always (unless you *really*really* know what you're
        doing!) use a qualified
        "except" clause. E.g.

        try:
        stuff
        except SomeParticularE xception:
        other_stuff

        Not:
        try:
        stuff
        except:
        other_stuff

        The bare "except" clause invites all kinds of silent, unexpected bad
        behavior.

        Comment

        • Brian Cole

          #5
          Re: check to see if value can be an integer instead of string

          Python uses "Exceptions " to catch these "Exceptiona l"
          situations:http://docs.python.org/tut/node10.html

          -Brian Cole

          On 17 Jan 2006 18:51:44 -0800, nephish@xit.net <nephish@xit.ne t> wrote:[color=blue]
          > thanks for the reply, but wont python fail out if you try to make an
          > integer out of what cant be an integer?
          > like this :
          >
          > var = int(abc)
          >
          > wont this crash ?
          >
          > --
          > http://mail.python.org/mailman/listinfo/python-list
          >[/color]

          Comment

          • nephish@xit.net

            #6
            Re: check to see if value can be an integer instead of string

            this looks like the solution i am looking for. thanks for the education
            by the way.
            i have a couple of other try / except clauses. Never thought of pulling
            it off like that.
            thanks very much, really simple.

            Comment

            • Steven D'Aprano

              #7
              Re: check to see if value can be an integer instead of string

              On Tue, 17 Jan 2006 18:02:52 -0800, nephish wrote:
              [color=blue]
              > Hello there,
              > i need a way to check to see if a certain value can be an integer. I
              > have looked at is int(), but what is comming out is a string that may
              > be an integer.[/color]

              Not in Python it isn't. int(value) returns an int, not a string.
              [color=blue]
              > i mean, it will be formatted as a string, but i need to
              > know if it is possible to be expressed as an integer.
              >
              > like this
              >
              > var = some var passed to my script
              > if var can be an integer :
              > do this
              > else:
              > change it to an integer and do something else with it.[/color]


              So, let's see if I understand your problem:

              if var can be an integer, you "do this" (whatever this is).

              If var *can't* be an integer, you change it to an integer anyway.


              [color=blue]
              > whats the best way to do this ?[/color]


              try:
              int(var)
              except ValueError:
              raise
              else:
              do_this()


              Or even simpler:

              int(var)
              do_this()


              --
              Steven.

              Comment

              • nephish@xit.net

                #8
                Re: check to see if value can be an integer instead of string

                it isn't really that i will want to change it to an integer anyway. the
                script uses a table to reference a value to a key, if the key is a
                group of letters, that code tells the script to do something. if the
                value is a number, it means an equipment failure. The thing is, all the
                values come out as strings (they are read from a text file).
                so what you put first with the try/except looks like my best answer.

                thanks,
                shawn

                Comment

                • Gerard Flanagan

                  #9
                  Re: check to see if value can be an integer instead of string

                  nephish@xit.net wrote:
                  [color=blue]
                  > it isn't really that i will want to change it to an integer anyway. the
                  > script uses a table to reference a value to a key, if the key is a
                  > group of letters, that code tells the script to do something. if the
                  > value is a number, it means an equipment failure. The thing is, all the
                  > values come out as strings (they are read from a text file).
                  > so what you put first with the try/except looks like my best answer.
                  >
                  > thanks,
                  > shawn[/color]

                  Shawn

                  Are you aware of the string method 'isdigit()' ?

                  vars = ["KEY_ONE", "KEY_2", "0", "1", "24", "00100"]
                  for var in vars:
                  if not var.isdigit():
                  print "OPTION: %s" % var
                  else:
                  print "EQUIPMENT FAILURE: %s" % var

                  OPTION: KEY_ONE
                  OPTION: KEY_2
                  EQUIPMENT FAILURE: 0
                  EQUIPMENT FAILURE: 1
                  EQUIPMENT FAILURE: 24
                  EQUIPMENT FAILURE: 00100

                  ( 'isdigit' != 'is_a_digit' rather 'isdigit' ==
                  'is_a_string_of _digits' )

                  Gerard

                  Comment

                  • Steven D'Aprano

                    #10
                    Re: check to see if value can be an integer instead of string

                    On Wed, 18 Jan 2006 04:23:17 -0800, nephish wrote:
                    [color=blue]
                    > it isn't really that i will want to change it to an integer anyway. the
                    > script uses a table to reference a value to a key, if the key is a
                    > group of letters, that code tells the script to do something. if the
                    > value is a number, it means an equipment failure. The thing is, all the
                    > values come out as strings (they are read from a text file).
                    > so what you put first with the try/except looks like my best answer.[/color]


                    def do_this():
                    print "Do this"

                    def do_that():
                    print "Doing something else"

                    code_table = { "abc": do_this, "def": do_that, "xyz": do_this }
                    error_table = { "001": "Broken widget", "002": "Overloaded doohickey"}

                    if code_table.has_ key(value_from_ hardware):
                    code_table[value_from_hard ware]()
                    else:
                    try:
                    print error_table[value_from_hard ware]
                    except KeyError:
                    raise CustomHardwareE rror("Unknown value!")


                    --
                    Steven.

                    Comment

                    • Marc 'BlackJack' Rintsch

                      #11
                      Re: check to see if value can be an integer instead of string

                      In <dqk8r0$ou2$1@n ewsreader3.netc ologne.de>, Claudio Grondi wrote:
                      [color=blue]
                      > No idea whats the best way to do and what in detail you want to achieve,
                      > but before others reply here, you can maybe start with something like this:
                      >
                      > intTheInt = None
                      >
                      > def checkIfStringCa nBeAnInteger(st rWithInt):
                      > global intTheInt
                      > try:
                      > intTheInt = int(strWithInt)
                      > if(type(intTheI nt)==type(1)):
                      > return True
                      > except:
                      > return False
                      > #:def[/color]

                      Please! Don't use ``global``. And why are you testing for type `int` if
                      you converted successfully to `int` just one line above!?

                      Also it's not a good idea to use a bare ``except``. If you mistype a name
                      within the ``try...except` ` the function will alwas return false because
                      the `NameError` is caught. The ``except`` will mask *any*
                      exception/error. This makes debugging more difficult than it should be.

                      Ciao,
                      Marc 'BlackJack' Rintsch

                      Comment

                      • nephish@xit.net

                        #12
                        Re: check to see if value can be an integer instead of string

                        Thanks guys,
                        No, i did not know about isdigit ?
                        very helpful. Thanks.

                        esp liked the "overloaded doohicky' bit.

                        thanks again.

                        Comment

                        Working...