[英]How to make a continuous alphabetic list python (from a-z then from aa, ab, ac etc)
[英]How to make input only accept a-z etc
我无法让我的输入只接受 az 和 AZ 字母。 这是我想出的
while(not(studentName == "END")):
studentName = input("What is the name of the student (END to finish) ")
if not re.match("^[a-z]*$", studentName):
print("Only letters are allowed")
elif len(studentName) == 0:
print("Insufficient characters. Please try again.")
else:
studentsNames.append(studentname)
但是我只是想出了一个错误“未定义”。 我该怎么办:C
我喜欢使用内置的字符串方法,而不是使用正则表达式。 其中之一是str.isalpha()
,当在字符串上调用时,如果字符串仅包含Az
,则返回True
。 所以而不是:
if not re.match("^[a-z]*$", studentName):
print("Only letters are allowed")
我只想写:
if not studentName.isalpha():
print("Only letters are allowed!")
您需要导入re
模块,并且必须将正则表达式更改为,
if not re.match(r"^[A-Za-z]+$", studentName):
只需在 python 脚本的顶部输入以下代码。
import re
您的正则表达式"^[az]*$"
将匹配零个或多个小写字母。 也就是说,它也会匹配空字符串,并且不会匹配只有大写字母的字符串,例如FOO
。
所以这个if not re.match("^[az]*$", studentName):
将为所有不能是空字符串或只包含小写字母的字符串返回true
。
您可以使用set和string.ascii_letters :
from string import ascii_letters
def is_all_characters(student_name):
return set(student_name) in set(ascii_letters)
isalpha() 适用于这个要求。
username = input("Enter Username: ")
if username.isalpha() is False:
print("Only Text allowed in Username")
else:
print("Welcome "+username)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.