首页 > 解决方案 > 检查字符串的特定字符是数字还是字母(python)

问题描述

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

标签: pythonstringif-statement

解决方案


你可以在这里使用正则表达式:

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

推荐阅读