0 votes
1 view
in Python by (43.4k points)

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

1 Answer

0 votes
by (97.6k points)

For checking whether a string represents an int, without using try/except if your string is a positive integer you can use .isdigit.This method will only work with positive numbers.

'16'.isdigit()

image

If your string contains negative integers then you can try the following way:

s = '-17'

s.startswith('-') and s[1:].isdigit() 

image

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...