我有一个问题,原来我想验证我所在国家的ID,即“ 00000000-0”,因为在脚本之前可以有7或8个数字,在脚本之后可以以0,1结尾,2,3,4,5,6,7,8,9,k。因此,我还没有找到一种只允许我接受该格式的方法。你能帮我吗?
我国的DNI示例:
18654675-6
19657346-k
1543564-0
我有这个代码
class instructor (models.Model):
_name = 'gym.instructor'
name = fields.Char (string = "Name", required = 'true')
telefono = fields.Integer (string = "Telephone +56", size = 9, required = True)
rut = fields.Char ()
address = fields.Char (string = "Address", required = True)
mail = fields.Char (string = "Email")
class_id = fields.Many2one (comodel_name = 'gym.clase', string = 'Class', required = False)
def digit_verifier (dni):
pat = re.compile ('^ \ d {7,8} - [0-9k]')
if pat.search (str (dni)) is not None:
return True
return False
record model = "ir.ui.view" id = "gym.instructor_list">
<field name = "name"> instructor list </ field>
<field name = "model"> gym.instructor </ field>
<field name = "arch" type = "xml">
<tree>
<field name = "id" />
<field name = "name" />
<field name="rut"/>
<field name = "telefono" />
<field name = "address" />
<field name = "mail" />
<field name = "class_id" />
</ tree>
</ field>
</ record>
答案 0 :(得分:3)
如果您想要这样的东西:
import re
def digito_verificador(dni):
pat = re.compile('^\d{7,8}-[0-9k]')
if pat.search(str(dni)) is not None:
return True
return False
或
import re
def digito_verificador(dni):
pat = re.compile('^\d{7,8}-[0-9k]')
return pat.findall(dni)
这两种方法都对您有用,如果他们不做详细说明!
给出Jacob Rodal
的答案,他首先想到了。
答案 1 :(得分:2)
我会使用正则表达式模式。例如,您可以尝试以下模式:
pattern = re.compile(r"^\d{7,8}-[0-9k]",re.M)
该模式将匹配具有7或8个数字,后接破折号,后接一位数字或k的任何字符串。它只会匹配行的开头或紧接换行符之后的行。如果这不符合您的用例,我建议您研究正则表达式,以便您可以修改我使用的模式。
它可以像这样使用:
import re
pattern = re.compile(r"^\d{7,8}-[0-9k]",re.M)
examples = """
matches:
18654675-6
19657346-k
1543564-0
not matches:
random text
186546755-6 (too many numbers)
19657346-c (invalid ending)
153564-0 (too few numbers)
"""
valid_ids = pattern.findall(examples)
print(valid_ids)
输出:
['18654675-6', '19657346-k', '1543564-0']