繁体   English   中英

为什么str.isdigit总是输出相反的结果

[英]Why does the str.isdigit always output the opposite result

def is_valid_zip(zip_code): """Returns whether the input string is a valid (5 digit) zip code """ if (len(zip_code) == 5) and (str.isnumeric == True): return True else : return False

几点讨论。 关于你的情况:

str.isnumeric == True

左侧的那个东西是函数本身,而不是调用给出结果的函数,后者是some_string.isnumeric()

函数对象等于 true 的可能性介于零和非常非常小的数字之间:-)

将布尔值与布尔常量进行比较也是多余的,因为比较的结果只是另一个布尔值。 在这种情况下你会在哪里停下来? 例如:

(((some_bool_value == True) == True) == True) != False ...

另一点,代码形式if cond then return true else return false可以替换为更简洁的return cond

还要记住, isnumeric()允许原始数字以外的其他内容,例如¾ 如果您只想要数字,那么使用另一种方法可能会更好。 您可能想改用isdigit() ,但即便如此,它也允许大多数人认为“正常”数字之外的其他东西,例如允许"90²10"作为邮政编码,大概是比佛利山庄更时尚的部分:-) .

如果您想要原始数字0-9 (这可能是您所针对的美国邮政编码的情况), isnumeric()isdigit()都不合适。


考虑到所有这些,该功能的实现可能如下:

def is_valid_zip(zip_code):
    if len(zip_code) != 5:
        return False
    return all([x in "1234567890" for x in zip_code])

首先,它应该是str.isnumeric() == True因为它正在调用 isnumeric 函数。 其次,您应该真正使用str.isdigit()

str.isnumeric()
在 Python 中,十进制字符(如:0、1、2..)、数字(如:下标、上标)和具有 Unicode 数值属性的字符(如:分数、罗马数字、货币分子)都被视为数字字符。 因此,即使是 1、2 和 3 的日语字符也会通过此检查。

str.isdigit()
另一方面,如果字符串中的所有字符都是数字,则 isdigit() 只会返回 True。 如果不是,则返回 False。

来源: https : //www.programiz.com/python-programming/methods/string/isdigit

它应该是zip_code.isnumeric()而不是str.isnumeric

另外,你为什么不使用正则表达式:

import re
RE_ZIP_CODE = re.compile(r'^[0-9]{5}$')  # or r'^\d{5}$' for all digit characters

def is_valid_zip(zip_code):
    
    return RE_ZIP_CODE.search(zip_code) is not None

这应该工作

def is_valid_zip(zip_code):
    """Returns whether the input string is a valid (5 digit) zip code
    """
    if len(zip_code) == 5 and zip_code.isnumeric():
        return True
    else:
        return False


print(is_valid_zip("98909"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM