如何在Python中检查字符串中是否包含数字值? [英] How can I check if a string has a numeric value in it in Python?

查看:3175
本文介绍了如何在Python中检查字符串中是否包含数字值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何检查字符串是否是Python中的数字?

Python - 将字符串解析为Float或Int

例如,我想检查字符串以及它是否不可转换为整数(使用 int()),我该如何检测?

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

推荐答案

使用 .isdigit()方法

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

引用文档:


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

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

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

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.

这篇关于如何在Python中检查字符串中是否包含数字值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆