Python调用isnumeric判断输入出错如何实现仅接受数字或字母的校验
问题原因
- 代码中
V.isnumeric没有加调用括号,访问的是方法对象本身而非执行校验逻辑,所有方法对象的布尔判定结果都为True,因此无论输入什么内容都会触发成立分支。 - 若要实现仅接受数字或字母的输入校验,可直接使用字符串内置的
isalnum()方法,该方法会判定字符串是否仅由数字、英文字母组成。
修正代码
仅判定输入为数字的场景
# input默认返回字符串,无需额外用str()转换 V = input('\n\tEnter\n\n\t') # 方法后加()执行调用 if V.isnumeric(): print(f'\n\tYour V is a numeric and it is "{V}"\n\t')
仅接受数字/字母输入的完整校验场景
V = input('\n\tEnter\n\n\t') if V.isalnum(): if V.isnumeric(): print(f'\n\tYour V is a numeric and it is "{V}"\n\t') else: print(f'\n\tYour V is a letter string and it is "{V}"\n\t') else: print('\n\tInvalid input: only numbers and letters are allowed\n\t')
补充说明
如果需要严格限制仅支持阿拉伯数字和英文字母,排除中文数字、全角字符等特殊字符,可以改用正则匹配实现:
import re V = input('\n\tEnter\n\n\t') if re.fullmatch(r'^[0-9a-zA-Z]+$', V): # 校验通过后的逻辑 pass
内容的提问来源于stack exchange,提问作者uucp007
相关产品推荐
相关产品推荐

