可能重复:
如何检查字符串是否为Python 中的数字?
Python - 将字符串解析为浮点数或整数
例如,我想检查一个字符串,如果它不能转换为整数(使用 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() 方法:
Use the .isdigit() method:
>>> '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 中检查字符串中是否包含数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
python:不同包下同名的两个模块和类python: Two modules and classes with the same name under different packages(python:不同包下同名的两个模块和类)
配置 Python 以使用站点包的其他位置Configuring Python to use additional locations for site-packages(配置 Python 以使用站点包的其他位置)
如何在不重复导入顶级名称的情况下构造python包How to structure python packages without repeating top level name for import(如何在不重复导入顶级名称的情况下构造python包)
在 OpenShift 上安装 python 包Install python packages on OpenShift(在 OpenShift 上安装 python 包)
如何刷新 sys.path?How to refresh sys.path?(如何刷新 sys.path?)
分发带有已编译动态共享库的 Python 包Distribute a Python package with a compiled dynamic shared library(分发带有已编译动态共享库的 Python 包)