Best way to check if string is an integer?

S

skanemupp

which is the best way to check if a string is an number or a char?
could the 2nd example be very expensive timewise if i have to check a
lot of strings?

this

value = raw_input()

try:
value = int(value)
except ValueError:
print "value is not an integer"


or:


c=raw_input("yo: ")
if c in '0123456789':
print "integer"
else:
print "char"



or some other way?
 
A

Andrew Warkentin

which is the best way to check if a string is an number or a char?
could the 2nd example be very expensive timewise if i have to check a
lot of strings?

this

value = raw_input()

try:
value = int(value)
except ValueError:
print "value is not an integer"


or:


c=raw_input("yo: ")
if c in '0123456789':
print "integer"
else:
print "char"



or some other way?
I always do it the first way. It is simpler, and should be faster. Also,
the second way will only work on single-digit numbers (you would have to
iterate over the entire string with a for loop to use it on numbers with
more than one digit).
 
M

Mark Dickinson

which is the best way to check if a string is an number or a char?
could the 2nd example be very expensive timewise if i have to check a
lot of strings?

You might be interested in str.isdigit:
S.isdigit() -> bool

Return True if all characters in S are digits
and there is at least one character in S, False otherwise.

Mark
 
J

John Machin

You might be interested in str.isdigit:


S.isdigit() -> bool

Return True if all characters in S are digits
and there is at least one character in S, False otherwise.

This doesn't cater for negative integers.
 
T

Tim Chase

I always do it the first way. It is simpler, and should be faster.

Ditto. Using int() is best. It's clear, it's correct, and it
should be as fast as it gets.
Also, the second way will only work on single-digit numbers
(you would have to iterate over the entire string with a for
loop to use it on numbers with more than one digit).

It also catches things like c="1234" but misses negative numbers
too. It's a bad solution on a number of levels. The isdigit()
method of a string does much of what int() does for testing "is
this an int" except that it too misses negative numbers.

-tkc
 
S

Steve Holden

John said:
This doesn't cater for negative integers.
No, it doesn't, but

s.isdigit() or (s[0] in "+-" and s[1:].isdigit) # untested

does. and *may* be quicker than other examples. Not that speed is
usually a concern in validation routines anyway ...

regards
Steve
 
S

Steve Holden

John said:
This doesn't cater for negative integers.
No, it doesn't, but

s.isdigit() or (s[0] in "+-" and s[1:].isdigit) # untested

does. and *may* be quicker than other examples. Not that speed is
usually a concern in validation routines anyway ...

regards
Steve
 
R

Roy Smith

This doesn't cater for negative integers.
No, it doesn't, but

s.isdigit() or (s[0] in "+-" and s[1:].isdigit) # untested

does.[/QUOTE]

I think this fails on " -1". So, then you start doing
s.strip().isdigit(), and then somebody else comes up with some other
unexpected corner case...

int(s) and catching any exception thrown just sounds like the best way.
 
E

ernie

No, it doesn't, but
s.isdigit() or (s[0] in "+-" and s[1:].isdigit) # untested

I think this fails on " -1". So, then you start doing
s.strip().isdigit(), and then somebody else comes up with some other
unexpected corner case...

int(s) and catching any exception thrown just sounds like the best way.[/QUOTE]

Another corner case: Is "5.0" an integer or treated as one?

regards,
ernie
 
P

Paddy

This doesn't cater for negative integers.
No, it doesn't, but
s.isdigit() or (s[0] in "+-" and s[1:].isdigit) # untested
does.
I think this fails on " -1". So, then you start doing
s.strip().isdigit(), and then somebody else comes up with some other
unexpected corner case...
int(s) and catching any exception thrown just sounds like the best way.

Another corner case: Is "5.0" an integer or treated as one?

regards,
ernie

In Python, 5.0 is a float "5.0" is a string, and you need to make your
mind up about what type you want "5.0" to be represented as in your
program and code accordingly.

- Paddy.
 
J

Jorgen Grahn

In Python, 5.0 is a float "5.0" is a string, and you need to make your
mind up about what type you want "5.0" to be represented as in your
program and code accordingly.

int('5.0') raises an exception rather than rounding or truncating to
5. That is probably what most people want, and it seems the original
poster wanted that, too.

I always use int(n). If I ever find a situation where I want another
syntax for integers for some specialized use, I'll approach it as a
normal parsing problem and use regexes and so on -- wrapped in a
function.

The problem becomes clearer if you look at floats. There are many
different ways to write a float[0], and Python parses them better and
faster than you and me.

/Jorgen

[0] There would have been more if Python had supported hexadecimal
floating-point literals, like (I believe) C does.
 
B

bowman

Jorgen said:
[0] There would have been more if Python had supported hexadecimal
floating-point literals, like (I believe) C does.

C99 does. On the other hand, it isn't a feature I sorely missed during the
first 20 years or so of C's history, but you could always do some creative
byte twiddling if the need arouse.
 
M

Martin Marcher

hmmm

int() does miss some stuff:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1E+1'

I wonder how you parse this?

I honestly thought until right now int() would understand that and
wanted to show that case as ease of use, I was wrong, so how do you
actually cast this type of input to an integer?

thanks
martin


--
http://tumblr.marcher.name
https://twitter.com/MartinMarcher
http://www.xing.com/profile/Martin_Marcher
http://www.linkedin.com/in/martinmarcher

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.
 
M

Martin Marcher

arg, as posted earlier:

int("10.0") fails, it will of course work with float("1E+1") sorry for
the noise...

hmmm

int() does miss some stuff:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1E+1'

I wonder how you parse this?

I honestly thought until right now int() would understand that and
wanted to show that case as ease of use, I was wrong, so how do you
actually cast this type of input to an integer?

thanks
martin


--
http://tumblr.marcher.name
https://twitter.com/MartinMarcher
http://www.xing.com/profile/Martin_Marcher
http://www.linkedin.com/in/martinmarcher

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.



--
http://tumblr.marcher.name
https://twitter.com/MartinMarcher
http://www.xing.com/profile/Martin_Marcher
http://www.linkedin.com/in/martinmarcher

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.
 
S

Stephen Cattaneo

1E+1 is short hand for a floating point number, not an interger.10.0

You could convert the float to an integer if you wanted (i.e. ceiling,
floor, rounding, truncating, etc.).

Cheers,

Steve

-----Original Message-----
From: Martin Marcher [mailto:[email protected]]
Sent: Tuesday, April 08, 2008 1:32 PM
To: (e-mail address removed)
Subject: Re: Best way to check if string is an integer?

hmmm

int() does miss some stuff:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1E+1'

I wonder how you parse this?

I honestly thought until right now int() would understand that and
wanted to show that case as ease of use, I was wrong, so how do you
actually cast this type of input to an integer?

thanks
martin


--
http://tumblr.marcher.name
https://twitter.com/MartinMarcher
http://www.xing.com/profile/Martin_Marcher
http://www.linkedin.com/in/martinmarcher

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.
 
S

Steve Holden

Martin said:
hmmm

int() does miss some stuff:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1E+1'

I wonder how you parse this?

I honestly thought until right now int() would understand that and
wanted to show that case as ease of use, I was wrong, so how do you
actually cast this type of input to an integer?

thanks
martin
int(float("1E+1")) # untested

regards
Steve
 

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,777
Messages
2,569,604
Members
45,202
Latest member
MikoOslo

Latest Threads

Top