Python中如何为input输入语句添加字符串类型校验约束
问题分析
- 原代码失效核心原因:Python 3 中
input()函数的返回值固定为字符串类型,无论用户输入数字、符号还是纯文本,type(student_name)永远是str类型,因此x!=str的判断永远为假,不会触发错误提示。 - 真实需求本质:你实际需要校验的不是输入的类型,而是输入的内容符合姓名的格式规则,因为即使用户输入
123这类明显不符合姓名要求的内容,从input()拿到的也是字符串类型的"123",原逻辑无法识别这类非法输入。
实现方案
可以通过正则匹配实现自定义的姓名格式校验,以下是两种常用场景的实现代码:
场景1:仅允许纯中文姓名(国内常用)
校验规则:仅支持汉字,长度限制2-8位
import re student_name = input("Enter the name of the student: ").strip() if re.fullmatch(r'^[\u4e00-\u9fa5]{2,8}$', student_name): print(student_name) else: print('invalid name')
场景2:支持中英文姓名(通用场景)
校验规则:支持汉字、大小写字母、中间空格,长度限制2-20位,禁止数字和特殊符号
import re student_name = input("Enter the name of the student: ").strip() if re.fullmatch(r'^[a-zA-Z\u4e00-\u9fa5\s]{2,20}$', student_name): print(student_name) else: print('invalid name')
内容的提问来源于stack exchange,提问作者Abhishek Shankar
相关产品推荐
相关产品推荐

