gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:37:07 32 4
gpt4 key购买 nike

例如,我想检查一个字符串,如果它不能转换为整数(使用 int()),我该如何检测?

最佳答案

使用 .isdigit() method :

>>> '123'.isdigit()
True
>>> '1a23'.isdigit()
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例如,是数字,但不是小数。

关于python - 如何在 Python 中检查字符串中是否包含数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12466061/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com