Determines whether the string is a valid Python identifier
Usage
The isidentifier()
method returns TRUE if the string is a valid identifier according to the language definition, and FALSE otherwise.
A valid identifier can only have alphanumeric characters a-z, A-Z, 0-9
and underscore _
. The first character of an identifier cannot be a digit. Also, identifier should not match a Python keyword (reserved identifier).
Syntax
string.isidentifier()
Examples
# Check if string 'totalCount' is a valid identifier
S = 'totalCount'
x = S.isidentifier()
print(x)
# Prints True
An identifier can contain an underscore but not a special character.
print('total_Count'.isidentifier())
# Prints True
print('total Count'.isidentifier())
# Prints False
print('total-Count'.isidentifier())
# Prints False
An identifier can contain a digit, except for the first character.
print('123totalCount'.isidentifier())
# Prints False
print('totalCount123'.isidentifier())
# Prints True
What If The String Is a Python Keyword?
Surprisingly, isidentifier()
returns True for a string that matches a Python keyword, even though it is not a valid identifier.
print('class'.isidentifier())
# Prints True
To test whether a string matches a Python keyword, use keyword.iskeyword()
from keyword import iskeyword
print(iskeyword('class'))
# Prints True
So, a string is considered a valid identifier if .isidentifier()
returns True and iskeyword()
returns False.