473,385 Members | 1,888 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Best way to check if string is an integer?

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?
Apr 5 '08 #1
16 14698
sk*******@yahoo.se wrote:
>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).
Apr 5 '08 #2
On Apr 5, 6:19*pm, skanem...@yahoo.se wrote:
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:
>>print str.isdigit.__doc__
S.isdigit() -bool

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

Mark
Apr 5 '08 #3
On Apr 6, 9:25 am, Mark Dickinson <dicki...@gmail.comwrote:
On Apr 5, 6:19 pm, skanem...@yahoo.se wrote:
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:
>print str.isdigit.__doc__

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.

Apr 6 '08 #4
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.
>if c in '0123456789':
print "integer"
else:
print "char"

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
Apr 6 '08 #5
John Machin wrote:
On Apr 6, 9:25 am, Mark Dickinson <dicki...@gmail.comwrote:
>On Apr 5, 6:19 pm, skanem...@yahoo.se wrote:
>>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:
>>>>print str.isdigit.__doc__
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.
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
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Apr 6 '08 #6
John Machin wrote:
On Apr 6, 9:25 am, Mark Dickinson <dicki...@gmail.comwrote:
>On Apr 5, 6:19 pm, skanem...@yahoo.se wrote:
>>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:
>>>>print str.isdigit.__doc__
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.
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
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Apr 6 '08 #7
In article <ma**************************************@python.o rg>,
Steve Holden <st***@holdenweb.comwrote:
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.
Apr 6 '08 #8
On Apr 6, 10:23 am, Roy Smith <r...@panix.comwrote:
In article <mailman.2927.1207447793.9267.python-l...@python.org>,
Steve Holden <st...@holdenweb.comwrote:
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
Apr 6 '08 #9
On Apr 6, 5:18 am, ernie <ernesto.ado...@gmail.comwrote:
On Apr 6, 10:23 am, Roy Smith <r...@panix.comwrote:
In article <mailman.2927.1207447793.9267.python-l...@python.org>,
Steve Holden <st...@holdenweb.comwrote:
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.
Apr 6 '08 #10
On Sat, 5 Apr 2008 22:02:10 -0700 (PDT), Paddy <pa*******@googlemail.comwrote:
On Apr 6, 5:18 am, ernie <ernesto.ado...@gmail.comwrote:
>On Apr 6, 10:23 am, Roy Smith <r...@panix.comwrote:
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?
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.

--
// Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.se R'lyeh wgah'nagl fhtagn!
Apr 6 '08 #11
Jorgen Grahn wrote:
[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.

Apr 6 '08 #12
byte twiddling if the need arouse.
I'm excited already :)

** Posted from http://www.teranews.com **
Apr 8 '08 #13
hmmm

int() does miss some stuff:
>>1E+1
10.0
>>int("1E+1")
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.
Apr 8 '08 #14
arg, as posted earlier:

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

On Tue, Apr 8, 2008 at 10:32 PM, Martin Marcher <ma****@marcher.namewrote:
hmmm

int() does miss some stuff:
>>1E+1
10.0
>>int("1E+1")
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.
Apr 8 '08 #15
1E+1 is short hand for a floating point number, not an interger.
>>float("1E+1")
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:ma****@marcher.name]
Sent: Tuesday, April 08, 2008 1:32 PM
To: py*********@python.org
Subject: Re: Best way to check if string is an integer?

hmmm

int() does miss some stuff:
>>1E+1
10.0
>>int("1E+1")
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.

Apr 8 '08 #16
Martin Marcher wrote:
hmmm

int() does miss some stuff:
>>>1E+1
10.0
>>>int("1E+1")
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
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Apr 8 '08 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: sinister | last post by:
Is there a PHP function to verify that a string validly represents an integer?
6
by: Cyrus D. | last post by:
Hi guys, I want to validate a string to make sure it contains only digits. 0001 = true 6669 = true 00a0 = false 6.665 = false What's the best way to go about doing that ?
5
by: Tony Vasquez | last post by:
I want to turn the string "100,144" to numbers, to use for resizeTo(100,144) <--- here. Please advice, or post scriptlette. Thanks Tony Vasquez
5
by: ief | last post by:
hi all, i'm trying to check the length of a numeric value in a string. this is what i need to do: I have a string "Mystring (253)" and a string "SecondString (31548745754)" Now i have to...
3
by: Oliver Saunders | last post by:
is there anyway to check if a string could be used a variable name. So return false if the first character isn't a letter or if it contains spaces etc. I started writing a function that would do...
2
by: CSharp | last post by:
Is it possible to find if lower 1st bit and 2nd bit in an 32-bit integer is set using regular expression in C# Example 1. Input Strings - 0, 1, 2 Result - Fai 2. Input Strings - 3, 7, ...
6
by: comp.lang.php | last post by:
I'm involved in a rather nasty debate involving a strange issue (whereby the exasperated tell me to RTFM even after my having done so), where this is insanely possible: print_r(is_int('1'));...
5
by: Cylix | last post by:
Is there any existing method in VB.NET or any 3-third party function can find out the language in a string? Let say, isChinese? isFrench?
5
by: zivon | last post by:
Hello everyone ! I made a price calculator for a guest house. I have diffrent sale campaigns, all the time, I made a table with campaign name and discount, for example: name "pensioners"...
2
by: gamernaveen | last post by:
I wanted to include a string invalid character check in my application. Like the field comment , if a user inserts any special characters (Except '' , '@' , '/' , '=' and numbers - alphabets) ,...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.