我正在尝试打印只包含字母、数字和"-";以及"_"并且长度在3到16个字符之间。
usernames = input().split(', ')
for word in usernames:
if 3 <= len(word) <= 16 and (c for c in word if (c.isalnum() or c == '_' or c == '-')) and ' ' not in word:
print(word)
输入:
Jeff, john45, ab, cd, peter-ivanov, @smith
输出必须为:
Jeff
John45
peter-ivanov
但取而代之的是:
Jeff
john45
peter-ivanov
@smith
为什么会这样?
(c for c in word if (c.isalnum() or c == '_' or c == '-'))
是一个包含所有这些字符的生成器。所有生成器都是真实的,所以这实际上并没有检查任何东西。
使用all()
函数来测试是否所有字符都符合该条件。然后就没有必要检查' ' not in word
,因为它不符合这个标准。
if 3 <= len(word) <= 16 and all(c.isalnum() or c == '_' or c == '-' for c in word):
您也可以使用正则表达式:
import re
for word in usernames:
if re.match(r'[w-]{3,}$', word):
print(word)