如何验证字符串?

问题描述 投票:0回答:1

我只是想知道如何编写验证字符串的代码?例如,用户输入邮政编码(字符串)。我必须确保它遵循 L#L#L# 格式 L-> 仅代表字母,#-> 仅代表数字(非小数)...如果不要求用户再次输入

python string format postal
1个回答
1
投票

字符串方法 更多信息

对于您的示例,您可以使用步骤 2 来切片字符串,检查每个字符串是否是数字/字母:

.isdecimal
检查构成 10 基数系统 (0-9) 的字符。

.isalpha
检查字母 (A-Z)

test_good = 'L5L5L5'
test_bad = 'LLLLLL'

def check_string(test):
    if test[0::2].isalpha() and test[1::2].isdecimal():
        return True
    else:
        return False

测试一下:

check_string(test_good)
>>>True

阴性测试:

check_string(test_bad)
>>>False

正则表达式 更多信息 正则表达式

Regex 执行模式匹配操作以及更多操作。在下面的示例中,我提前编译了模式,以便它看起来干净并且可以在需要时重复使用。

我还使用

re.fullmatch()
,它需要提供的整个字符串匹配,而不仅仅是其中的一部分。它本身会返回
None
或匹配对象,所以我检查它是否存在(意味着它匹配)并返回 True 或如果不存在(无)返回 False。

import re

def match(test):
    re_pattern = re.compile('[A-Z][0-9][A-Z][0-9][A-Z][0-9]')
    if re.fullmatch(re_pattern, test):
        return True
    else:
        return False
© www.soinside.com 2019 - 2024. All rights reserved.