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
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) .
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With