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

N

nephish

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
 
C

Claudio Grondi

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
 
N

nephish

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 ?
 
G

gry

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.
 
N

nephish

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.
 
S

Steven D'Aprano

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()
 
N

nephish

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
 
G

Gerard Flanagan

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
 
S

Steven D'Aprano

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!")
 
M

Marc 'BlackJack' Rintsch

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
 
N

nephish

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

esp liked the "overloaded doohicky' bit.

thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top