Sunday, June 24, 2018

How can I check if a string has a numeric value in it in Python?





Possible Duplicate:
How do I check if a string is a number in Python?
Python - Parse String to Float or Int






For example, I want to check a string and if it is not convertible to integer(with int()), how can I detect that?


Answer




Use the .isdigit() method:



>>> '123'.isdigit()
True
>>> '1a23'.isdigit()
False


Quoting the documentation:





Return true if all characters in the string are digits and there is at least one character, false otherwise.




For unicode strings or Python 3 strings, you'll need to use a more precise definition and use the unicode.isdecimal() / str.isdecimal() instead; not all Unicode digits are interpretable as decimal numbers. U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...