字符串检查函数if else ass

2024-04-28 22:51:03 发布

您现在位置:Python中文网/ 问答频道 /正文

初学者。我的代码应该能够检查一个给定的号码是否是xxx-xx-xxxx格式的。我认为if语句在某个地方是错误的。欢迎任何提示谢谢。在

def checkit(a):
    if a is (int[0:2]+"-"+ int[4:5] +"-"+int[7:8]):
        print("True")
    else:
        print("False")

assert checkit(832-38-1847)
assert not checkit(832- 23-  1 847)
print("/n(Good job!)")

错误消息:

^{pr2}$

Tags: 代码if格式地方错误assert语句号码
2条回答

尝试使用正则表达式:

import re
def checkit(a):
    return bool(re.match("^[0-9]{3}-[0-9]{2}-[0-9]{4}$", a))

checkit("832-38-1847")
#> True
checkit("832- 23-  1 847")
#> False

reprexpy package于2018-09-23创建

^{pr2}$

错误消息告诉您您正在尝试为类型“int”下标。根据我推断你想要做的,切片(下标)你的变量“a”,然后验证切片是一个整数(int),最简单的for可能是类似于int(a[0:2]) + "-" + int(a[4:5]) + "-" + int(a[7:8])的整数(int)。然而,这种技术有一些主要的缺陷。如果任何切片不能转换为“int”类型,python将抛出ValueError: invalid literal for int() with base 10: <whatever value threw the error>。您可以使用“try”“except”块稍微改进一下:

try:
    int(a[0:2]) # etc...
except:
    print("Not the correct format")

但这是相当麻烦的,如果您需要评估更复杂的东西,它可能会变得非常麻烦和大量的代码行来正确评估。在

验证表达式的一种更简洁的方法是使用正则表达式。正则表达式非常简洁,是检查值、匹配格式和值类型(仅限int或string)的综合方法。在

另外,您试图传递给checkit函数的参数值会被python误解为数学表达式。您需要用单引号或双引号括住参数值。在

这里有一种检查所需格式和值类型的可能方法(注意:这个示例有点做作,以便在断言失败时查看assert语句的实际运行情况):

^{pr2}$

如果您实际上不需要assert语句,那么验证值的方法可能会更短:

import re
def checkit(a):
    pattern = r'^([0-9]{3})-{1}([0-9]{2})-{1}([0-9]{4})$'
    match = re.fullmatch(pattern, a)
    if match != None:
        print("True")
        print("\n(Good job!)")
    else:
        print("False")
        print("Not the correct format or values or both")

要了解更多信息并更好地理解正则表达式,请访问以下关于regexp的链接

这个网站也可能有用PyRegex

顺便说一下,要像您在示例中使用的方法一样解析和验证字符串,可以执行以下操作:

def checkit(a):
    try:
        slicedVal = str(int(a[0:3])) + '-' + str(int(a[4:6])) + '-' + str(int(a[7:11]))
        print(slicedVal)
        # Caution!
        # If you want to match exactly the number of digits in the last portion of xxx-xx-xxxx variable
        # the slice or the assert statement will not catch this error or fail
        # Slicing a string with a number greater than it's length will pass without errors
        # e.g.
        # >>> print('I will pass'[0:2000])
        # I will pass
        assert slicedVal == a, "FAIL"
        print("True")
        return slicedVal
    except:
        print("False")

success = '832-38-1847'
assert success == checkit(success), "This won't fail this assertion test"
# True

# Should technically fail if formatting match is required
doesNotFail = '832-38-184'
assert doesNotFail == checkit(doesNotFail), "This won't fail this assertion test"
# True

willFail = '832- 23-  1 847'
assert willFail == checkit(willFail), "This one will fail for sure"
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AssertionError: This one will fail for sure

print("/n(Good job!)")
#
# (Good job!)

相关问题 更多 >