python - 检查字符串的特定字符是数字还是字母(python)
问题描述
例如,我希望用户输入邮政编码。但是,它有限制,例如邮政编码的长度必须为 5;第一个、第三个和第五个字符应该是数字,而其他必须是字母。否则,程序应显示错误。我想我需要写一个条件,但我还没有想出代码,它将检查字符串的特定字符是数字还是字母。
解决方案
你可以在这里使用正则表达式:
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
推荐阅读
- unity3d - 如何在 Unity 中替换层次结构中的某些内容?
- keras - 如何在 keras 自定义模型中使用 scklearn RandomForestRegressor 模型?
- tensorflow - memmap 数组到 pytorch 和梯度累积
- python - 多层次查询深度嵌套复杂的 JSON 数据
- json - 如何从 Json 文件 discord.py 中读取数据
- reactjs - 在 React.js 中将用户数据从 useEffect() 保存到 useContext() 之前加载页面
- python - 如何将结构中的给定残基突变为 biopythhon 中的不同氨基酸?
- kernel - 是否有 64 位 UEFI ELF 引导加载程序?
- winapi - MFC:如何保存和恢复 CEditView 滚动位置以便正确滚动内容?
- python - 更改顺序 x 轴 matplotlib