免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 24861 | 回复: 14

isdigit()不能判断负数 [复制链接]

论坛徽章:
0
发表于 2008-10-06 10:42 |显示全部楼层
>>> '-1'.isdigit()
False
>>> '1'.isdigit()
True


请问怎么判断输入的是数字,包括输入的是负数时,谢谢

论坛徽章:
0
发表于 2008-10-06 11:57 |显示全部楼层
可以使用:
try:
    int(a)
except:
    pass

论坛徽章:
0
发表于 2008-10-06 14:07 |显示全部楼层

回复 #2 limodou 的帖子

除了这个还有没有其它的方法,为什么isdigit()不能判断负数为数字呢?

论坛徽章:
0
发表于 2008-10-06 14:36 |显示全部楼层
isdigit的docstring:
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.'
可见,isdigit逐个判断字符串中的每个字符,是否所有的都是数字(也就是说'0'到'9')?

'-1'.isdigit()返回False是因为'-'不是一个digit。

如果楼主想判断输入的in_str是否整数,可以这样:
if (in_str[0] == '-' and in_str[1:] or in_str).isdigit():
    ...

当然也可以这样:
import re
if re.match(r'^-?\d+$', in_str):
    ...

如果输入的可能是小数,可以这样:
import re
if re.match(r'^-?(\.\d+|\d+(\.\d+)?)', in_str)
    ...

论坛徽章:
0
发表于 2008-10-06 15:25 |显示全部楼层
原帖由 limodou 于 2008-10-6 11:57 发表
可以使用:
try:
    int(a)
except:
    pass



感觉这个是最简单的,但还是觉得不优雅。

论坛徽章:
0
发表于 2008-10-07 11:11 |显示全部楼层
>>> a=10;
>>> isinstance(a,int)
True
>>> a=-10;
>>> isinstance(a,int)
True
>>> a='asdf'
>>> isinstance(a,int)
False
>>>

论坛徽章:
0
发表于 2008-10-07 11:12 |显示全部楼层
楼上的不行,lz要判断的不是对象的类型,而是字符串是否是数值表示。

论坛徽章:
0
发表于 2008-10-10 16:36 |显示全部楼层
那看来只能正则匹配了.

论坛徽章:
0
发表于 2008-10-10 23:20 |显示全部楼层
原帖由 leefurong 于 2008-10-6 14:36 发表
isdigit的docstring:
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.'
可见,isdigit逐个判断字符串中的每个字符,是否所有的都是数字(也就是 ...



想起来了,string[0] == 'a' 可以这样:string.startswith('a')
更优雅

论坛徽章:
0
发表于 2011-07-26 11:49 |显示全部楼层
支持6L isinstance(STRING,TYPE)....
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP