Best way to check if string is an integer?
Steve Holden
steve at holdenweb.com
Sat Apr 5 22:08:45 EDT 2008
John Machin wrote:
> On Apr 6, 9:25 am, Mark Dickinson <dicki... at gmail.com> wrote:
>> On Apr 5, 6:19 pm, skanem... at 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/
More information about the Python-list
mailing list