我正在制作一个包含一些验证的程序
number = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
def UsernameValidation():
New_Username_char = ("")
Valid = 0
if not len(New_Username) <= 4:
print("Username too short")
for i in range(0, len(New_Username) - 2):
New_Username_char[i] = str(New_Username[i])
if New_Username_char.islower():
print("Username should be in uppercase")
Valid += 1
if New_Username[len(New_Username)] not in number or New_Username[len(New_Username)-1] not in number:
print("The Username should be followed by two number")
Valid += 1
出现了这些错误
追踪(最近一次通话): 文件“C:\ Users \ Thomas \ Desktop \ FIle Handling \ Mini Project.py”,第71行,in 创建帐号() 在CreateAccount中输入文件“C:\ Users \ Thomas \ Desktop \ FIle Handling \ Mini Project.py”,第60行 GetUsername() 在GetUsername中的文件“C:\ Users \ Thomas \ Desktop \ FIle Handling \ Mini Project.py”,第41行 UsernameValidation() 在UsernameValidation中的文件“C:\ Users \ Thomas \ Desktop \ FIle Handling \ Mini Project.py”,第33行 如果New_Username [len(New_Username)]不在数字中,或者New_Username [len(New_Username)-1]不在数字中: IndexError:字符串索引超出范围
当我打印出它显示New_Username
的{{1}}的长度时(New_Username中应该有一些内容)
答案 0 :(得分:1)
以下是您的功能的更新版本。正如您在下面的评论中所看到的,它有一些问题。
def UsernameValidation(new_username):
new_username = str(new_username)
if len(new_username) <= 4:
print("Username too short")
return False
if any(x.islower() for x in new_username):
print("Username should be in uppercase")
return False
if not new_username[-2:].isnumeric():
print("The Username should be followed by two numbers")
return False
print('Password accepted!')
return True
print(UsernameValidation('and')) # too short - REJECTED
print(UsernameValidation('ANDrEW')) # contains lowercase - REJECTED
print(UsernameValidation('ANDREW')) # no numbers - REJECTED
print(UsernameValidation('ANDREW12')) # ACCEPTED
建议:
str()
,any()
)UsernameValidation
的函数应该返回一个基于名称number = [...]
)答案 1 :(得分:-1)
New_Username[len(New_Username) - 1]
是New_Username中的最后一个字符,您尝试通过说New_Username[len(New_Username)]
字符串中第一个字符的索引是0,下一个1,然后是2,然后是3,依此类推,例如:
String: 'H', 'e', 'l', 'l', 'o'
Index: 0 , 1 , 2 , 3 , 4
len(string)
返回字符串中的字符数,在下面的示例中,字符数为5,并且5超出范围,例如:
String: 'H', 'e', 'l', 'l', 'o'
Index: 0 , 1 , 2 , 3 , 4 , 5
^
There is no character at index 5, so an IndexError is thrown