You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:18:03