python - 我怎样才能在python中输入只接受大写字母和数字
问题描述
基本上我需要获取一个变量作为用户输入(ch),当然它只能包含大写字母和数字。我试图将用户的输入大写,即使他以小写格式提供它们,效果很好,但现在我必须确保他没有使用任何符号(就像你在 forbidenCh 中看到的那样),但我的想法没有奏效在这里帮助我,您可以使用任何您想要的方法,只要它完成程序的目的和thnx
这是我的尝试:
ch=str(input("only give letters and numbers"))
ch= ch.upper()
forbidenCh="!#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
for i in forbidenCh:
for j in ch:
if i == j:
ch=str(input("u didn't put captilized letters and numbers !!"))
ch= ch.upper()
else:
break
解决方案
可能只检查允许的字符可能更容易:
import string
allowedCharacters = string.digits + string.ascii_uppercase
# allowedCharacters >> 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
ch = str(input("only give letters and numbers"))
ch = ch.upper()
# check if all characters of the input are in allowedCharacters!
if not all(c in allowedCharacters for c in ch):
print("u didn't put captilized letters and numbers !!")
else:
print("input is fine")
推荐阅读
- flutter - WebRTC setRemoteDescription Session 在 Flutter 中为 Null 错误
- python - 如何在类中调用函数?
- c# - 更改面板背景图像后,我想在重新运行表单时保存它
- c# - 从 Firestore 检索数据时遇到问题
- javascript - html2canvas 在 php 循环中不起作用
- c# - Unity3d 2020.3.10f1 和 Android 10 - 想要通过从下载文件夹中读取我的 GPX 文件来访问它们
- django - 在 django 视图中使用 select_related 会增加查询时间
- node.js - 如何防止过滤后的流断开连接?
- python-3.x - 无法重命名文件,函数 os.rename 给出错误,“FileNotFoundError”
- android-studio - 如何调用调试器以获取完整的墓碑堆栈跟踪