Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a string represents an int, without using try/except?

Is there any way to tell whether a string represents an integer (e.g., '3', '-17' but not '3.14' or 'asfasfas') Without using a try/except mechanism?

is_int('3.14') == False is_int('-7')   == True 
like image 899
Adam Matan Avatar asked Aug 12 '09 11:08

Adam Matan


People also ask

How do you check if an item is an int?

Check if object is int or float : isinstance() You can get the type of an object with the built-in function type() . You can also check if an object is of a particular type with the built-in function isinstance(object, type) .

How do you check if input is integer or string?

Approach used below is as follows − Input the data. Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int. Print the resultant output.

How do you check if a string contains an integer in Python?

str. isdigit() returns True if all the characters in the given string are digits, False otherwise. If stringExample contains at least a number, then the above code returns True because chr. isdigit() for chr in stringExample has at least one True in the iterable.


1 Answers

with positive integers you could use .isdigit:

>>> '16'.isdigit() True 

it doesn't work with negative integers though. suppose you could try the following:

>>> s = '-17' >>> s.startswith('-') and s[1:].isdigit() True 

it won't work with '16.0' format, which is similar to int casting in this sense.

edit:

def check_int(s):     if s[0] in ('-', '+'):         return s[1:].isdigit()     return s.isdigit() 
like image 190
SilentGhost Avatar answered Sep 29 '22 20:09

SilentGhost