且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python中检查字符串中是否包含数字值?

更新时间:2023-02-26 13:18:21

使用 .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.