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

假装没事ソ 提交于 2019-11-27 06:33:34

问题


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?


回答1:


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.




回答2:


You can always try it:

try:
   a = int(yourstring)
except ValueError:
   print "can't convert"

Note that this method outshines isdigit if you want to know if you can convert a string to a floating point number using float



来源:https://stackoverflow.com/questions/12466061/how-can-i-check-if-a-string-has-a-numeric-value-in-it-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!