如何限制输入而不导入重新
大家好,尝试询问用户名,但只能使用字母、数字或_。如果提供其他任何信息,我需要再次询问。这是我到目前为止所拥有的,但是当我尝试运行时,它只是继续运行而不是完成。 因此,在第一个问题之后,如果我输入像“jack”这样的用户名,它应该只打印用户名:jack,但它只是不断询问代码中的第二个问题“请输入用户名(仅字母和数字)我该如何解决这个问题” ?
Username = input ("What is your username?")
while Username != "^[A-Za-z0-9]*$":
Username = input('Please enter a username(only letters and numbers)')
print("Username: ", Username)
hi all trying to ask for username and only letters or numbers or _ can be used. if anything else is provided i need to ask again. this is what i have so far but when i try to run it just keeps going instead of completing.
so after the first question, if i enter username like "jack" it should just print username: jack, but instead it just keeps asking the second question in the code 'Please enter a username(only letters and numbers) how do i fix this?
Username = input ("What is your username?")
while Username != "^[A-Za-z0-9]*quot;:
Username = input('Please enter a username(only letters and numbers)')
print("Username: ", Username)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以有两种方法。
代码:
There can be two ways.
str.isalnum()
. This is easy short and better than the previous.Code:
对这个 https://stackoverflow.com/a/71506891/18248018 答案的一个小修改是替换该行
虽然不是 Username.replace('_', '').isalnum():
让其他一切保持不变。
如果这是您的意图,这将允许用户名仍然包含下划线。
.replace(old, new)
返回一个新字符串(保持原始字符串不变),并将子字符串old
的所有实例替换为字符串new
。这意味着上面修改后的代码行对相当于删除下划线的用户名输入的字符串调用.isalnum()
,并检查所有剩余字符是否都是字母数字。否则,
.isalnum()
将拒绝包含下划线的输入。A small modification to this https://stackoverflow.com/a/71506891/18248018 answer would be to substitute the line
while not Username.replace('_', '').isalnum():
leaving everything else the same.
This would allow the username to still contain underscores, if this is your intent.
.replace(old, new)
returns a new string (leaving the original one unchanged) with all instances of the substringold
replaced with stringnew
. This means that the modified line of code above calls.isalnum()
on a string equivalent to the Username input stripped of underscores, and checks whether all the remaining characters are alphanumeric.Otherwise,
.isalnum()
will reject input containing underscores.