<p>错误消息告诉您您正在尝试为类型“int”下标。根据我推断你想要做的,切片(下标)你的变量“a”,然后验证切片是一个整数(int),最简单的for可能是类似于<strong><code>int(a[0:2]) + "-" + int(a[4:5]) + "-" + int(a[7:8])</code></strong>的整数(int)。然而,这种技术有一些主要的缺陷。如果任何切片不能转换为“int”类型,python将抛出<code>ValueError: invalid literal for int() with base 10: <whatever value threw the error></code>。您可以使用“try”“except”块稍微改进一下:</p>
<pre><code>try:
int(a[0:2]) # etc...
except:
print("Not the correct format")
</code></pre>
<p>但这是相当麻烦的,如果您需要评估更复杂的东西,它可能会变得非常麻烦和大量的代码行来正确评估。在</p>
<p>验证表达式的一种更简洁的方法是使用正则表达式。正则表达式非常简洁,是检查值、匹配格式和值类型(仅限int或string)的综合方法。在</p>
<p>另外,您试图传递给checkit函数的参数值会被python误解为数学表达式。您需要用单引号或双引号括住参数值。在</p>
<p>这里有一种检查所需格式和值类型的可能方法(注意:这个示例有点做作,以便在断言失败时查看assert语句的实际运行情况):</p>
^{pr2}$
<p>如果您实际上不需要assert语句,那么验证值的方法可能会更短:</p>
<pre><code>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")
</code></pre>
<p>要了解更多信息并更好地理解正则表达式,请访问以下关于<a href="https://docs.python.org/3/library/re.html" rel="nofollow noreferrer">regexp</a>的链接</p>
<p>这个网站也可能有用<a href="http://www.pyregex.com/" rel="nofollow noreferrer">PyRegex</a></p>
<p>顺便说一下,要像您在示例中使用的方法一样解析和验证字符串,可以执行以下操作:</p>
<pre><code>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!)
</code></pre>