Exercise: Usernames

Validation functions are where edge cases pile up. This one has a strong test suite, the kind you should learn to write. Read the rules, then list your own test cases before you code.

A valid username:

  • is 3 to 16 characters long, inclusive
  • uses only ASCII letters a-z and A-Z, digits 0-9 and underscore _
  • starts with a letter
  • does not end with an underscore
  • has no two underscores in a row

Watch for the trap: str.isalpha() and str.isdigit() say yes to "é", "日" and "²", because they accept any Unicode letter or digit. The string module has ascii_letters and digits, or you can use str.isascii().

Exercise: write is_valid_username to follow the rules. Before you press Check, test it yourself in the demo block: empty, one character, exactly 3 and 16, 17, a space, "josé". Press Check to run the tests.