identifier = re.compile('^[^\\d\\W]\\w*\\Z', re.UNICODE)
tests = ['a', 'a1', '_a1', '1a', 'aa$%@%', 'aa bb', 'aa_bb', 'aa\n']
for test in tests:
    result = re.match(identifier, test)
print('%s\t= %s' % (test, result is not None))
Regular expression to confirm whether a string is a valid identifier in Python