Is there any way to tell whether a string represents an integer (eg, '3'
, '-17'
but not '3.14'
or 'asfasfas'
) Without using尝试/排除机制?
is_int('3.14') == False
is_int('-7') == True
原文由 Adam Matan 发布,翻译遵循 CC BY-SA 4.0 许可协议
Is there any way to tell whether a string represents an integer (eg, '3'
, '-17'
but not '3.14'
or 'asfasfas'
) Without using尝试/排除机制?
is_int('3.14') == False
is_int('-7') == True
原文由 Adam Matan 发布,翻译遵循 CC BY-SA 4.0 许可协议
对于正整数,您可以使用 .isdigit
:
>>> '16'.isdigit()
True
但它不适用于负整数。假设您可以尝试以下操作:
>>> s = '-17'
>>> s.startswith('-') and s[1:].isdigit()
True
它不适用于 '16.0'
格式,在这个意义上类似于 int
转换。
编辑:
def check_int(s):
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
原文由 SilentGhost 发布,翻译遵循 CC BY-SA 2.5 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
4 回答2.3k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
如果你真的只是对到处使用
try/except
感到厌烦,请编写一个辅助函数:这将是更多的代码来准确覆盖 Python 认为整数的所有字符串。我说这只是pythonic。