Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k 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 (106k 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

0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...