检查字符串的特定字符是数字还是字母(python)

时间:2020-11-04 09:38:10

标签: python string if-statement

例如,我希望用户输入邮政编码。但是,它有一些限制,例如邮政编码的长度必须为5;第一,第三和第五个字符应为数字,而其他字符必须为字母。否则,程序应显示错误。我想我需要写一个条件,但是我还没有拿出代码,该代码将检查字符串的特定字符是数字还是字母。

2 个答案:

答案 0 :(得分:2)

您可以在此处使用正则表达式:

postcode = "1A2B3"
if re.search(r'^\d[A-Za-z]\d[A-Za-z]\d$', postcode):
    print("postal code is valid")

上面的正则表达式用于:

^             from the start of the postal code
    \d        match a digit
    [A-Za-z]  match a letter
    \d        match a digit
    [A-Za-z]  match a letter
    \d        match a digit
$             end of the postal code

答案 1 :(得分:0)

您可以将邮政编码分成一个字符列表,并使用isnumeric()和isalpha()检查字符串邮政编码中其特定位置的每个字符的类型。

postal_code = '1A2B3'


def split(word):
    return [char for char in word]

def postal_code_checker(postal_code):

    # check the length of the post_code
    if len(postal_code) != 5:
        return False
    
    #split the postal code  ['1', 'A', '2', 'B', '3']
    char_list = split(postal_code)
    
    #check the type for the specific position
    if char_list[1].isnumeric() or char_list[3].isnumeric():        
        return False

    if char_list[0].isalpha() or char_list[2].isalpha() or char_list[4].isalpha() :        
        return False
    
    #if all is OK return True
    return True


if postal_code_checker(postal_code):
    print('no error')
else:
    print('There was an error')
相关问题