Python String isidentifier() Method

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

Example: Check if string ‘totalCount’ is a valid identifier

S = 'totalCount'
x = S.isidentifier()
print(x)	# True

An identifier can contain an underscore but not a special character.

Example:

print('total_Count'.isidentifier())   # True
print('total Count'.isidentifier())   # False
print('total-Count'.isidentifier())   # False

An identifier can contain a digit, except for the first character.

Example:

print('123totalCount'.isidentifier()) # False
print('totalCount123'.isidentifier()) # 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.

Example:

print('class'.isidentifier())   # True

To test whether a string matches a Python keyword, use keyword.iskeyword()

Example:

from keyword import iskeyword
print(iskeyword('class'))	# True

So, a string is considered a valid identifier if .isidentifier() returns True and iskeyword() returns False.