By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,182 Members | 1,138 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,182 IT Pros & Developers. It's quick & easy.

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

P: n/a
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

Jan 18 '06 #1
Share this Question
Share on Google+
11 Replies


P: n/a
ne*****@xit.net wrote:
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

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 checkIfStringCanBeAnInteger(strWithInt):
global intTheInt
try:
intTheInt = int(strWithInt)
if(type(intTheInt)==type(1)):
return True
except:
return False
#:def

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

for strWithInt in lstTestCases:
intTheInt = None
if checkIfStringCanBeAnInteger(strWithInt):
print '"'+strWithInt+'"', ' is an integer', intTheInt
else:
print '"'+strWithInt+'"', ' is NOT an integer'
Claudio
Jan 18 '06 #2

P: n/a
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 ?

Jan 18 '06 #3

P: n/a
gry
ne*****@xit.net wrote:
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. The "int" builtin function never returns any value but 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.
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.
whats the best way to do this ?


The "pythonic" way might be something like:

var=somestring
try:
do_something(int(var)) #just try to convert var to integer and
proceed
except ValueError:
do_something_else(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 SomeParticularException:
other_stuff

Not:
try:
stuff
except:
other_stuff

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

Jan 18 '06 #4

P: n/a
Python uses "Exceptions" to catch these "Exceptional"
situations:http://docs.python.org/tut/node10.html

-Brian Cole

On 17 Jan 2006 18:51:44 -0800, ne*****@xit.net <ne*****@xit.net> wrote:
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

Jan 18 '06 #5

P: n/a
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.

Jan 18 '06 #6

P: n/a
On Tue, 17 Jan 2006 18:02:52 -0800, nephish wrote:
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.
Not in Python it isn't. int(value) returns an int, not a string.
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.

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.
whats the best way to do this ?

try:
int(var)
except ValueError:
raise
else:
do_this()
Or even simpler:

int(var)
do_this()
--
Steven.

Jan 18 '06 #7

P: n/a
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

Jan 18 '06 #8

P: n/a
ne*****@xit.net wrote:
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


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

Jan 18 '06 #9

P: n/a
On Wed, 18 Jan 2006 04:23:17 -0800, nephish wrote:
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.

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_hardware]()
else:
try:
print error_table[value_from_hardware]
except KeyError:
raise CustomHardwareError("Unknown value!")
--
Steven.

Jan 18 '06 #10

P: n/a
In <dq**********@newsreader3.netcologne.de>, Claudio Grondi wrote:
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 checkIfStringCanBeAnInteger(strWithInt):
global intTheInt
try:
intTheInt = int(strWithInt)
if(type(intTheInt)==type(1)):
return True
except:
return False
#:def


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
Jan 19 '06 #11

P: n/a
Thanks guys,
No, i did not know about isdigit ?
very helpful. Thanks.

esp liked the "overloaded doohicky' bit.

thanks again.

Feb 6 '06 #12

This discussion thread is closed

Replies have been disabled for this discussion.