<p>不需要将所需的字符串格式硬编码到数组索引或正则表达式中。您只需获取给定的格式字符串并使用它来解析数字。然后,您可以根据各自的格式分别检查每个字符,并使用这些数字添加到校验和中。你知道吗</p>
<p>举个例子:</p>
<pre><code>def check(s):
# the format string:
# "#" digit character, " ": space character
fmt = "#### #### #### ####"
# check length of input string
if len(s) != len(fmt):
return False
# compute checksum and validate format
checksum = 0
# iterate "zipped" format and input string
for f,i in zip(fmt, s):
if f == "#":
# expecting i to be digit
try:
checksum += int(i)
except ValueError:
# i is not a digit
return False
elif i != " ":
# expected i to be space (but it's not)
return False
# validate checksum
return not checksum%10
</code></pre>
<p>供参考:</p>
<ul>
<li><a href="https://docs.python.org/2/library/functions.html#int" rel="nofollow">https://docs.python.org/2/library/functions.html#int</a></li>
<li><a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow">https://docs.python.org/2/library/functions.html#zip</a></li>
</ul>