Search code examples
pythonspecial-charactersalphanumeric

Why Python prints special characters @#$ etc. when I specifically said not to do so?


I'm trying to print the usernames that contain only letters, numbers, "-" and "_" and are between 3 and 16 characters long.

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)

Input:

Jeff, john45, ab, cd, peter-ivanov, @smith

Output must be:

Jeff
John45
peter-ivanov

But instead is:

Jeff
john45
peter-ivanov
@smith

Why is that so?


Solution

  • (c for c in word if (c.isalnum() or c == '_' or c == '-')) is a generator containing all those characters. All generators are truthy, so this is not actually checking anything.

    Use the all() function to test if all the characters fit that criteria. And then there's no need to check ' ' not in word, since that doesn't meet this criteria.

        if 3 <= len(word) <= 16 and all(c.isalnum() or c == '_' or c == '-' for c in word):
    

    You could also also use a regular expression:

    import re
    
    for word in usernames:
        if re.match(r'[\w-]{3,}$', word):
            print(word)