
[英]How can I not allow letters, and only allow numbers in an input on python 3?
[英]How to restrict the user to input only letters and numbers in Python 3?
我需要编写一个算法来验证玩家的用户名并检查该名称是否已在外部文本文件中注册。
playerName = input('Please enter a player name')
如何限制用户只能输入字母和数字?
您不能限制用户可以输入的内容(至少通过输入),但您可以使用 while 循环重复输入请求,直到用户正确输入
正如@peer 所说,您可以在while 循环中使用正则表达式。 没有办法用输入命令来做到这一点。
代码示例:
import re
playerName = '_'
while(not re.match("^[A-Za-z0-9]*$", playerName)):
playerName = input('Please enter a player name (Only letters and numbers)')
print("PlayerName: ", playerName)
编辑
正如@Joe Ferndz 在评论中所写,您可以使用 isalnum() 方法检查您的 playerName 是否为字母数字,因此您甚至不需要使用正则表达式
playerName = '_'
while(not playerName.isalnum()):
playerName = input('Please enter a player name (Only letters and numbers)')
print("PlayerName: ", playerName)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.