Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
5 views
in Python by (10.2k points)
edited by

Can someone tell me a method to check how can I represent a string as a number in Python?

I am using this function right now:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

This method is slow and clunky. So please help me with it. 

1 Answer

0 votes
by (46k points)
edited by

It's wrong to say that method is "slow and clunky", but if you want another method then use isdigit() function:

>>> q = "14634"
>>> q.isdigit()
True
>>> w = "074spam"
>>> w.isdigit()
False

You can use unicode too, but that's your own preference. 

Related questions

0 votes
2 answers
asked May 30, 2019 in Python by Anvi (10.2k points)
+6 votes
3 answers
0 votes
1 answer
+3 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...