我如何检查一个字符串在Python中是否有数值?

可能重复:
如何检查字符串是否是Python中的数字?
Python - 将字符串解析为Float或Int

例如,我想检查一个字符串,如果它不能转换为整数(与int() ),我怎么能检测到?


使用.isdigit()方法:

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

引用文档:

如果字符串中的所有字符都是数字并且至少有一个字符,则返回true,否则返回false。

对于unicode字符串或Python 3字符串,您需要使用更精确的定义并使用unicode.isdecimal() / str.isdecimal() 。 并非所有的Unicode数字都可以解释为十进制数字。 例如,U + 00B2 SUPERSCRIPT 2是一个数字,但不是小数。


你可以随时try它:

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

请注意,如果您想知道是否可以使用float将字符串转换为浮点数,则此方法会超过isdigit

链接地址: http://www.djcxy.com/p/48417.html

上一篇: How can I check if a string has a numeric value in it in Python?

下一篇: If strings are immutable in .NET, then why does Substring take O(n) time?