我的意思是什么?

2024-09-30 22:20:09 发布

您现在位置:Python中文网/ 问答频道 /正文

def CodelandUsernameValidation(s):
  if len(s)>4 and len(s)<25 and s[0].isalpha() and [i for i in s if i.isalnum() or i=="_"]!=[] and s[-1]!="_":
    return True
  else:
    return False
# keep this function call here 
print(CodelandUsernameValidation(input()))

Tags: orandinfalsetrueforlenreturn
2条回答

它在s中生成字母数字或下划线字符的列表。该代码实际上是不正确的,因为如果任何字符是字母数字或下划线,它将通过,而其目的肯定是所有字符都必须是字母数字或下划线。这里有一个更好的写作方法:

def CodelandUsernameValidation(s):
  return 4 < len(s) < 25 and s[0].isalpha() and all(i.isalnum() or i=='_' for i in s) and s[-1] != '_'

print(CodelandUsernameValidation(input()))

它是一个list comprehension如果您展开,它将如下所示->

result = []
for i in s: # will fetch element one by one from iterable
    if i.isalnum() or i=="_": # checking condition
        result.append(i) # if true, then append it to the list

上述代码可重写为-

result = [i for i in s if i.isalnum() or i=="_"]

相关问题 更多 >